在使用Laravel中的phpexcel
读取文件时,碰到一个问题:
代码:
Excel::load($file, function ($reader)
{
$results = $reader->get()->toArray();
dd($reader);
});

当使用上述代码读取下方表格时,读取到的结果是:
array:6 [
0 => array:8 [
0 => null
"hgc" => "HGC-20171026002"
"sop" => 40.0
"ng" => 100.0
"post_cycles" => 21.0
"ngul" => 25.0
"ul" => 4.0
"bp" => 2.0 ]
1 => array:8 []
2 => array:8 []
3 => array:8 []
4 => array:8 []
5 => array:8 []
可以看到,这样读取到的数组,只有首行表头为英文,或者是包含英文,才能读取到该列的内容
经查,发现在项目config目录下,有一个excel.php
的配置文件,在文件中有一行
/*
|--------------------------------------------------------------------------
| Sheet heading conversion
|--------------------------------------------------------------------------
|
| Convert headings to ASCII
| Note: only applies to 'heading' settings 'true' && 'slugged'
|
*/
'to_ascii' => true,
将该行改为false,问题解决。
ps:如果文件夹下没有excel.php
的配置文件,可以运行
php artisan vendor:publish --provider="Maatwebsite\Excel\ExcelServiceProvider"
生成配置文件。
修改后可以看到:

同时发现,在配置文件中的
/*
|--------------------------------------------------------------------------
| Has heading
|--------------------------------------------------------------------------
|
| The sheet has a heading (first) row which we can use as attribute names
|
| Options: true|false|slugged|slugged_with_count|ascii|numeric|hashed|trans|original
|
*/
'heading' => 'slugged',
/*
|--------------------------------------------------------------------------
| First Row with data or heading of data
|--------------------------------------------------------------------------
|
| If the heading row is not the first row, or the data doesn't start
| on the first row, here you can change the start row.
|
*/
'startRow' => 1,
heading
行改为false,startRow
行改为0,可以让首行以值的形式读取出来

另:经查,也可以用指定编码读取excel文件
$fileType = mb_detect_encoding($content , array('UTF-8','GBK','LATIN1','BIG5'));//获取当前文本编码格式
Excel::load('file.csv',function($reader){
$rows = $reader->all();
……
},$fileType);//以指定的编码格式打开文件
网友评论