Laravel讀取Excel

fyonecon發表於2020-11-11

-

1. 下載依賴:https://github.com/PHPOffice/PHPExcel ;

2. 下載完成後,將PHPExcel資料夾放在laravel的vendor目錄下;

3. 在你需要使用的控制器引用:

use PHPExcel_IOFactory;
use PHPExcel;

4. 例子:讀取Excel:

封裝:

    // 讀取excel
    // $excel_file是excel檔案的絕對路徑;$start_row是起始行,預設2;$end_row是截至行,預設最大行
    public function excel_to_array($excel_file=null, $start_row = null, $end_row = null){

        $test_data = [
            'excel_file'=> $excel_file,
            'start_row'=> $start_row,
            'end_row'=> $end_row,
        ];

        if (!$excel_file){
            $state = 0;
            $msg = 'Excel路徑引數不全';
            $content = [];
        }else{

            //載入excel檔案
            $filename = $excel_file;
            $objPHPExcelReader = PHPExcel_IOFactory::load($filename);

            $sheet = $objPHPExcelReader->getSheet(0); // 讀取第一個工作表(編號從 0 開始,sheet)
            if (!$end_row){
                $highestRow = $sheet->getHighestRow(); // 取得最大行數
            }else{
                $highestRow = $end_row;
            }
            $highestColumn = $sheet->getHighestColumn(); // 取得最大列數

            $arr = ['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']; // 目標列標號

            if (!$start_row){ // 預設從第二行讀
                $start_row = 2;
            }
            $res_arr = [];
            for ($row = $start_row; $row <= $highestRow; $row++) { // 一次讀取一列
                $row_arr = [];
                for ($column = 0; $arr[$column] != 'F'; $column++) {
                    $val = $sheet->getCellByColumnAndRow($column, $row)->getValue();
                    $row_arr[] = $val;
                }

                $res_arr[] = $row_arr;
            }

            $state = 1;
            $msg = 'Excel讀取完成';
            $content = $res_arr;

        }

        return [
            'state'=> $state,
            'msg'=> $msg,
            'test_data'=> $test_data,
            'content'=> $content,
        ];

    }

呼叫excel_to_array($excel_file)即可例如:

$excel_file = '/home/wwwroot/default/xxxxxx/vendor/phpexcel/Excel/1.xlsx';
$array = $excel->excel_to_array($excel_file);

var_dump($array);

結果:

-

-

相關文章