thinkphp5使用PhpOffice導入excel

安裝擴展

composer require phpoffice/phpspreadsheet

類文件引入擴展

use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Shared\Date;

導入方法

public function import(){
        //實例化xls類
        $reader = new Xls();
        try{
            $file = request()->file('fname');
            if(!$file){
                $this->error = '請上傳文件';
                return false;
            }
            //加載上傳的xls文件
            $spreadsheet = $reader->load($file->getPathname());
            //獲取當前使用的sheet
            $sheet = $spreadsheet->getActiveSheet();
        }catch (\PhpOffice\PhpSpreadsheet\Reader\Exception $e){
            Log::info('錯誤信息'.$e->getMessage());
            $this->error = $e->getMessage();
            return false;
        }
        
        //文件列數判定
        $countColumn = $sheet->getHighestColumn();  //總列數
        if ($countColumn != 'Z') {
            $this->error = '文件內容不合規';
            return false;
        }
        //文件行數判定
        $countRow = $sheet->getHighestRow();  //總行數
        $countRow = $countRow - 1;
        if ($countRow <= 0) {
            $this->error = '文件數據爲空';
            return false;
        }
        
        //循環處理
        foreach ($sheet->getRowIterator(2) as $k=>$row){
            $rowIndex = $row->getRowIndex();  //當前行
            //獲取所有參數
            $aaa = $sheet->getCellByColumnAndRow(1,$rowIndex)->getValue()??'';
            $bbb = $sheet->getCellByColumnAndRow(2,$rowIndex)->getValue()??'';
            $ccc = $sheet->getCellByColumnAndRow(3,$rowIndex)->getValue()??'';
            //...
            //...
            //...
            $this->save(['aaa'=>$aaa,'bbb'=>$bbb,'ccc'=>$ccc]);
        }
    }   
    
        

這是根據自己的已有項目整理出的文檔,總體方案沒有問題,如果有細節問題,歡迎指正.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章