5

我只想获取我的 excel 第一列,该列将是列名。

我正在使用此代码

Excel::load($request->file, function ($reader) use($request) {

$torarray=$reader->toArray();
            $line0 = $torarray[0];
            $headers = array_keys($line0);
            $excel_header=$headers;
        });

有时它有效,但有时无效。当不使用某些文件时,我在下面写并且可以工作

$torarray=$reader->toArray();
            $line0 = $torarray[0][0];
            $headers = array_keys($line0);
            $excel_header=$headers;
        });

我不明白什么是正确的解决方案。

4

5 回答 5

10

谢谢@mahmoud-zalt

只是想分享我如何在 Laravel 5.5 中使用它:

$reader = Excel::load(storage_path() . '/uploads/tracking-number/' . $fileName)->get();
$headerRow = $reader->first()->keys()->toArray();

JSON

["date","reference_no","tracking_notrace_webhttpwww.17track.com_for_eub_and_httpwww.cacesapostal.com_for_swiss_post","destination_country","receiver","tel","state","city","post_code","address","weightkg","quantity","valueusd","description","parcelquantity",0]

var_export

array (
  0 => 'date',
  1 => 'reference_no',
  2 => 'tracking_notrace_webhttpwww.17track.com_for_eub_and_httpwww.cacesapostal.com_for_swiss_post',
  3 => 'destination_country',
  4 => 'receiver',
  5 => 'tel',
  6 => 'state',
  7 => 'city',
  8 => 'post_code',
  9 => 'address',
  10 => 'weightkg',
  11 => 'quantity',
  12 => 'valueusd',
  13 => 'description',
  14 => 'parcelquantity',
  15 => 0,
)

print_r

Array
(
    [0] => date
    [1] => reference_no
    [2] => tracking_notrace_webhttpwww.17track.com_for_eub_and_httpwww.cacesapostal.com_for_swiss_post
    [3] => destination_country
    [4] => receiver
    [5] => tel
    [6] => state
    [7] => city
    [8] => post_code
    [9] => address
    [10] => weightkg
    [11] => quantity
    [12] => valueusd
    [13] => description
    [14] => parcelquantity
    [15] => 0
)
于 2017-09-21T09:18:32.440 回答
8

这段代码对我有用:

$results = Excel::selectSheetsByIndex(0)->load($file)->get();
echo "<pre>";
var_dump($results->getHeading());
echo "</pre>";
于 2017-10-26T15:04:27.797 回答
1

尝试这个:

/**
 * @param \SplFileInfo $file
 *
 * @return  Array
 */
public function run(SplFileInfo $file)
{
    $excelFile = Excel::load($file);

    $excelData = $excelFile->all();

    return (($excelData->first())->keys())->toArray();
}
于 2017-01-05T21:27:06.573 回答
1

对于 maatwebsite excel 的第 3 版,您可以通过以下方法获取标题:

use Maatwebsite\Excel\HeadingRowImport;

$headings = (new HeadingRowImport)->toArray(file);

插入文件路径代替 file 关键字。

于 2020-12-03T15:36:22.470 回答
0

只是想分享一些更优化的方法(这是 v2.1 解决方案):

Excel::load($file->path(), function (LaravelExcelReader $reader) {

    /** @var RowCollection $singleRow */
    $singleRow = $reader->takeRows(1)->get(); // no need to parse whole sheet for the headings
    $headings = $singleRow->getHeading();

    // Do validation. Throw exception.

    $reader->takeRows(false); // set the limit back to unlimited
})->get();
于 2018-10-06T16:34:47.410 回答