phpspreadsheet 導出導入excel簡單封裝


1.composer 安裝

  

composer require phpoffice/phpspreadsheet 1.8.2

  因為要兼容php5.6,所以是用的1.8.2版本

2.在公共函數文件中引入頭文件

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Style\Alignment;

3.定義導出封裝函數

if (!function_exists('downLoadExcel')){
    /**
     * 導出excel
     * @param $name excel名稱
     * @param $titles 標題 [['name'=>'姓名'],['gender'=>'性別']]
     * @param array $data
     * @throws \PhpOffice\PhpSpreadsheet\Exception
     * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception
     */
    function downLoadExcel($name, $titles, $data=[])
    {
        $count = count($titles);  //計算表頭數量
        $spreadsheet = new Spreadsheet();
        $styleArray = [
            'alignment' => [
                'horizontal' => Alignment::HORIZONTAL_CENTER_CONTINUOUS,
                'vertical' => Alignment::VERTICAL_CENTER,
            ],
        ];
        $sheet = $spreadsheet->getActiveSheet();
        for ($i = 65; $i < $count + 65; $i++) {     //數字轉字母從65開始,循環設置表頭
            $sheet->getStyle(strtoupper(chr($i)))->applyFromArray($styleArray);
            $sheet->getCell(strtoupper(chr($i)).'1')->getStyle()->getFont()->setBold(true);
            $index = $i - 65;
            $sheet->setCellValue(strtoupper(chr($i)) . '1',  $titles[$index][key($titles[$index])] );
        }
        
        /*--------------開始從數據庫提取信息插入Excel表中------------------*/
        foreach ($data as $key => $item) {             //循環設置單元格:
            //$key+2,因為第一行是表頭,所以寫到表格時   從第二行開始寫
            for ($i = 65; $i < $count + 65; $i++) {     //數字轉字母從65開始:
                $sheet->setCellValue(strtoupper(chr($i)) . ($key + 2),$item[key($titles[$i - 65])]);
                $spreadsheet->getActiveSheet()->getColumnDimension(strtoupper(chr($i)))->setAutoSize(true);
            }
        }
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="' . $name . '.xlsx"');
        header('Cache-Control: max-age=0');
        $writer = IOFactory::createWriter($spreadsheet,'Xlsx');
        $writer->save('php://output');
        //刪除清空
        $spreadsheet->disconnectWorksheets();
        unset($spreadsheet);
        exit;
    }
}

4.定義導入封裝函數

 

if (!function_exists('importExcel')){
    
    /**
     * 導入excel
     * @param $filePath 文件路徑
     * @param $cols 要導入的列 從1開始 $cols = [['1' => 'id'],['2' =>'name']];
     * @param int $sheetIndex sheet索引,默認從0開始
     * @return array
     * @throws \PhpOffice\PhpSpreadsheet\Exception
     * @throws \PhpOffice\PhpSpreadsheet\Reader\Exception
     */
    function importExcel($filePath, $cols, $sheetIndex = 0){

        $reader = IOFactory::createReader('Xlsx');
        $reader->setReadDataOnly(TRUE);
        $spreadsheet = $reader->load($filePath); //載入excel表格

        $sheetCount =  $spreadsheet->getSheetCount();
        if ($sheetIndex >= $sheetCount - 1){
            exit('sheet不存在');
        }
        $worksheet = $spreadsheet->getSheet($sheetIndex);
        $highestRow = $worksheet->getHighestRow(); // 總行數
        $lines = $highestRow - 2;
        if ($lines <= 0) {
            exit('Excel表格中沒有數據');
        }
        $data = [];
        for ($row = 2; $row <= $highestRow; $row++) {
            for ($i = 0; $i < count($cols); $i ++){
                $index = key($cols[$i]);
                $key = array_values($cols[$i])[0];
                $data[$row][$key] = $worksheet->getCellByColumnAndRow($index, $row)->getValue(); //學號
            }
        }
        return array_values($data);
    }

}

 

5.導出測試使用

$titles = [['name'=>'姓名'],['gender'=>'性別']];
$data = [
    ['name'=>'小黑','gender'=>'男']
];
downLoadExcel('測試',$titles,$data);

 6.導入測試使用

    excel如下

   $path = ROOT_PATH.DS.'public'.DS.'excel'.DS.'student.xlsx';
        if (is_file($path)){
            $cols = [['2' => 'name'],['3' =>'gender'],['4' => 'class']];
            $data = importExcel($path,$cols);
            halt($data);
        }

col是第幾列對應數組的key,這樣就只會獲取excel的姓名,性別,班級的數據


免責聲明!

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



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