1. 程式人生 > >ThinkPHP5.1上傳excel檔案並使用phpexcel讀取表格資料

ThinkPHP5.1上傳excel檔案並使用phpexcel讀取表格資料

首先在工程內使用composer安裝phpexcel:

composer require phpoffice/phpexcel

html部分:

<input type="file" id="img">
<input type="button" value="生成excel" onclick="create_excel">

js部分(formdata上傳):

function upload_excel(){
    let imgfile = $('#img')[0].files[0];
    let formdata = new FormData();
    formdata.append('imgfile',imgfile);
    $.ajax({
        url: "{:url('test/read_excel')}",
        data: formdata,
        dataType: 'json',
        type: 'post',
        contentType: false,
        processData: false,
        success: function(res){
            //程式碼塊
        }
    });
}

後端控制器接收檔案並呼叫讀取方法:

//獲取上傳檔案(此處應判斷檔案是否合法,可自行新增判斷條件)
$imgfile = input('file.imgfile');

//生成路徑和檔案(路徑可自定義,TP5.0版本可直接使用常量ROOT_PATH和DS)
$imgpath = Env::get('root_path').'public'.DIRECTORY_SEPARATOR.'uploads'.DIRECTORY_SEPARATOR.'excel.xls';
$imgfile->move(Env::get('root_path').'public'.DIRECTORY_SEPARATOR.'uploads','excel.xls',true);

//讀取並返回資料
$data = read_excel($imgpath);
return $data;

上面的read_excel為自定義方法,用於讀取excel表格中的資料,引數為檔案路徑

function read_excel($filename)
{
    //設定excel格式
    $reader = PHPExcel_IOFactory::createReader('Excel2007');
    //載入excel檔案
    $excel = $reader->load($filename);
    //讀取第一張表
    $sheet = $excel->getSheet(0);
    //獲取總行數
    $row_num = $sheet->getHighestRow();
    //獲取總列數
    $col_num = $sheet->getHighestColumn();

    $data = []; //陣列形式獲取表格資料
    for($col='A';$col<=$col_num;$col++)
    {
        //從第二行開始,去除表頭(若無表頭則從第一行開始)
        for($row=2;$row<=$row_num;$row++)
        {
            $data[$row-2][] = $sheet->getCell($col.$row)->getValue();
        }
    }
    return $data;
}

表格獲取資料如下: