【问题标题】:Why Laravel-Excel reads first row as column name为什么 Laravel-Excel 将第一行读取为列名
【发布时间】:2017-03-21 08:35:13
【问题描述】:

我需要读取一个.xls 文件并将其放入一个数组中。我正在使用 laravel-excel 包来读取 excel 文件。

我有一个这样的 Excel 文件:

我需要一个这样的数组:

[
 '9921234567' => 'First Text',
 '9929876544' => 'Second Text',
 '9927654321' => 'Third Text',
 '9928765432' => 'Fourth Text',

]

到目前为止我所做的尝试:

 Excel::load('sample.xls', function($reader) {
     $reader->dd();
 });

问题:

问题在于它将第一行读取为列!

0 => RowCollection {#619
      #title: "Sheet1"
      #items: array:3 [
        0 => CellCollection {#623
          #title: null
          #items: array:2 [
            9921234567 => 9929876544.0
            "first_text" => "Second Text"
          ]
        }
        1 => CellCollection {#624
          #title: null
          #items: array:2 [
            9921234567 => 9927654321.0
            "first_text" => "Third Text"
          ]
        }
        2 => CellCollection {#625
          #title: null
          #items: array:2 [
            9921234567 => 9928765432.0
            "first_text" => "Fourth Text"
          ]
        }
      ]
    }

看,我不想将第一行值算作列名!

任何帮助将不胜感激。

【问题讨论】:

    标签: php laravel phpexcel laravel-excel


    【解决方案1】:

    您在文档中链接了答案

    作为属性的表格标题 默认情况下,excel文件的第一行将用作属性。

    您可以更改配置 excel::import.heading 中的默认值。可用选项有:true|false|slugged|ascii|numeric|hashed|trans|original

    我从未使用过 laravel,只是将其设置为 false 并检查会发生什么。

    【讨论】:

      【解决方案2】:

      documentation 说:

      默认情况下,Excel 文件的第一行将用作属性

      所以,我推荐使用noHeading函数:

      Excel::load('sample.xls', function($reader) {
           $reader->noHeading();
           $reader->dd();
       });
      

      【讨论】:

        【解决方案3】:

        您需要遍历每一行。之后,您可以在遍历所有列时创建自定义数组

        Excel::load('sample.xls', function($reader) {
            $reader->each(function($sheet) {
                // Loop through all rows
                $sheet->each(function($row) {
                    // Loop through all columns
                });
            });
        })
        

        这只是 excel 导入的基本代码,您需要根据您的示例对其进行调整。

        希望对你有帮助

        【讨论】:

        • 不不...同样的问题
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多