美文网首页
laravel phpexcel无法读取excel中中文表头列数

laravel phpexcel无法读取excel中中文表头列数

作者: 如梦又似幻 | 来源:发表于2019-02-13 16:49 被阅读0次

    在使用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);//以指定的编码格式打开文件
    

    相关文章

      网友评论

          本文标题:laravel phpexcel无法读取excel中中文表头列数

          本文链接:https://www.haomeiwen.com/subject/pzedeqtx.html