0

我需要读取一个.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"
          ]
        }
      ]
    }

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

任何帮助将不胜感激。

4

3 回答 3

6

您在文档中链接了答案

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

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

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

于 2017-03-21T08:42:21.090 回答
1

文档说:

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

所以,我建议使用noHeading功能:

Excel::load('sample.xls', function($reader) {
     $reader->noHeading();
     $reader->dd();
 });
于 2019-02-07T16:51:43.653 回答
0

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

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

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

希望能帮助到你

于 2017-03-21T08:43:08.703 回答