TP5.1 簡單學會導入導出Excel


下載

 

composer require phpoffice/phpexcel

 

 

 

 

一般導出都都是 數據庫某張表 的記錄

 

 

 

 

測試類

 public function test()
    {
        $pro = new ProductModel();
        $list = $pro->field('id,title,class_id,imgs_url,content,create_time')->selectOrFail();
        $xlsName = "用戶表"; // 文件名
        $xlsCell = [        // 列名
            ['id', '序號'],
            ['title', '標題'],
            ['class_id', '分類id'],
            ['imgs_url', '圖片路徑'],
            ['content', '富文本'],
            ['create_time', '添加時間']
        ];// 表頭信息
        $this->downloadExcel($xlsName, $xlsCell, $list);// 傳遞參數

    }

 

封裝類, 建議對着一張空白Excel 來看

protected function downloadExcel($Title, $CellNameList, $TableData)
    {
        $xlsTitle    = iconv('utf-8', 'gb2312', $Title);  // excel標題
        $fileName    = $Title;                  // 文件名稱
        $cellNum     = count($CellNameList);    // 單元格名 個數
        $dataNum     = count($TableData);       // 數據 條數

        $obj = new PHPExcel();
        $originCell = [                           // 所有原生名
            'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
            'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
        ];

        //getActiveSheet(0) 獲取第一張表
        $obj->getActiveSheet(0)
            ->mergeCells('A1:' . $originCell[$cellNum - 1] . '1');       //合並單元格A1-F1 變成新的A1

        $obj->getActiveSheet(0)->setCellValue('A1', $fileName);      // 設置第一張表中 A1的內容

        for ($i = 0; $i < $cellNum; $i++) {                                     // 設置第二行 ,值為字段名
            $obj->getActiveSheet(0)
                ->setCellValue($originCell[$i] . '2', $CellNameList[$i][1]);      //設置 A2-F2 的值
        }

        // Miscellaneous glyphs, UTF-8  循環寫入數據
        for ($i = 0; $i < $dataNum; $i++) {
            for ($j = 0; $j < $cellNum; $j++) {                         // 設置第三行 ,每一行為 數據庫一條數據
                $obj->getActiveSheet(0)                                 // 設 A3 值, 值為$TableData[0]['id']
                    ->setCellValue($originCell[$j] . ($i + 3), $TableData[$i][$CellNameList[$j][0]]);
            }
        }
        //居中
        $obj->getActiveSheet(0)->getDefaultStyle()->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);

        ob_end_clean();//這一步非常關鍵,用來清除緩沖區防止導出的excel亂碼
        header('pragma:public');
        header('Content-type:application/vnd.ms-excel;charset=utf-8;name="' . $xlsTitle . '.xlsx"');  
        header("Content-Disposition:attachment;filename=$fileName.xlsx");   //"xls"參考下一條備注
        $objWriter = \PHPExcel_IOFactory::createWriter($obj, 'Excel2007');

        //"Excel2007"生成2007版本的xlsx,"Excel5"生成2003版本的xls 調用工廠類
        return $objWriter->save('php://output');
    }

 

PHP7.3會報continue錯誤 ,把對應文件的continue 改成 continue2 就好.

 

效果: 

 

導入更加簡單

 

 

1.文件上傳

 public function test()
    {
        header("content-type:text/html;charset=utf-8");

        $file = request()->file('excel');
        $info = $file->validate(['size' => 1048576, 'ext' => 'xls,xlsx'])->move('./excels');    //文件上傳

        if ($info) {                                            //上傳成功

            $fileName = $info->getSaveName();                    //文件名
            $filePath = PUBLIC_PATH . '/excels/' . $fileName;    //絕對路徑
            $suffix = $info->getExtension();                     //后綴

            //判斷哪種類型
            if ($suffix == "xlsx")
                $reader = PHPExcel_IOFactory::createReader('Excel2007');
            else
                $reader = PHPExcel_IOFactory::createReader('Excel5');   //xls

        } else
            return $file->getError();

        $excel = $reader->load($filePath, $encode = 'utf-8');       //載入excel文件
        $this->dataImport($excel);                                  //導入數據庫
    }

 

2.存入數據庫

public function dataImport($excel)
    {
        //讀取第一張表
        $sheet = $excel->getSheet(0);
        //獲取總行數
        $row_num = $sheet->getHighestRow();     // 數據條數
        //獲取總列數
        $col_num = $sheet->getHighestColumn();  // 字段個數

        //1、excel 方式操作
        $data = [];
        for ($i = 3; $i <= $row_num; $i++) {                        //i=3是為了 去除大標題和標題
            $data[$i]['id'] = $sheet->getCell("A" . $i)->getValue();
            $data[$i]['title'] = $sheet->getCell("B" . $i)->getValue();
            $data[$i]['class_id'] = $sheet->getCell("C" . $i)->getValue();
            $data[$i]['imgs_url'] = $sheet->getCell("D" . $i)->getValue();
            $data[$i]['content'] = $sheet->getCell("E" . $i)->getValue();
            $data[$i]['create_time'] = strtotime($sheet->getCell("F" . $i)->getValue());

            //excel時間操作
            //$time = date('Y-m-d H:i',\PHPExcel_Shared_Date::ExcelToPHP($sheet->getCell("B".$i)->getValue()));
            //$data[$i]['time'] = strtotime($time);
        }
        dump($data);

        //2、數組操作
        $list = [];
        $arr = $sheet->toArray();
        array_shift($arr);      //去除大標題
        array_shift($arr);      //去除標題

        foreach ($arr as $k => $v) {
            $list[$k]['id'] = $v[0];
            $list[$k]['title'] = $v[1];
            $list[$k]['class_id'] = $v[2];
            $list[$k]['imgs_url'] = $v[3];
            $list[$k]['content'] = $v[4];
            $list[$k]['create_time'] = strtotime($v[5]);
        }
        dump($list);

        (new ProductModel)->insertAll($data);
    }

 

效果

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM