简体   繁体   English

为什么Laravel-Excel读取第一行作为列名

[英]Why Laravel-Excel reads first row as column name

I need to read an .xls file and put it into an array. 我需要读取.xls文件并将其放入数组。 I'm using laravel-excel package for reading excel files. 我正在使用laravel-excel软件包读取Excel文件。

I have a Excel file like this : 我有一个这样的Excel文件:

在此处输入图片说明

I need to have an array like this : 我需要一个像这样的数组:

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

]

What I have tried so far : 到目前为止我尝试过的是:

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

Problem: 问题:

The problem is it reads the first row as column! 问题是它将第一行读取为列!

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"
          ]
        }
      ]
    }

Look, I don't want to first row values count as column name! 看,我不想将第一行的值计为列名!

Any helps would be great appreciated. 任何帮助将不胜感激。

You linked answer in documentation 您在文档中链接了答案

Table heading as attributes By default the first row of the excel file will be used as attributes. 表格标题作为属性默认情况下,excel文件的第一行将用作属性。

You can change the default inside the config excel::import.heading. 您可以在excel :: import.heading配置中更改默认值。 Available options are: true|false|slugged|ascii|numeric|hashed|trans|original 可用选项为:true | false |慢速| ascii |数字|哈希| trans |原始

I never used laravel but just set it to false and check what will happen. 我从未使用过laravel,而只是将其设置为false并检查会发生什么。

You need to loop thru each row. 您需要遍历每一行。 After that you can create your custom array when you loop thru all columns 之后,当您遍历所有列时可以创建自定义数组

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

This is just basic code for excel import, you need to adjust it to your example. 这只是excel导入的基本代码,您需要根据示例进行调整。

Hope it helps 希望能帮助到你

The documentation says: 文件说:

By default the first row of the Excel file will be used as attributes 默认情况下,Excel文件的第一行将用作属性

So, I recommend to use noHeading function: 因此,我建议使用noHeading函数:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM