我想只获得我的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;
});
我无法理解什么是正确的解决方案。
答案 0 :(得分:9)
谢谢@ 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
)
答案 1 :(得分:6)
此代码对我有用:
$results = Excel::selectSheetsByIndex(0)->load($file)->get();
echo "<pre>";
var_dump($results->getHeading());
echo "</pre>";
答案 2 :(得分:1)
试试这个:
/**
* @param \SplFileInfo $file
*
* @return Array
*/
public function run(SplFileInfo $file)
{
$excelFile = Excel::load($file);
$excelData = $excelFile->all();
return (($excelData->first())->keys())->toArray();
}
答案 3 :(得分: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();
答案 4 :(得分:0)
对于maatwebsite excel版本3,您可以通过以下方法获得标题:
use Maatwebsite\Excel\HeadingRowImport;
$headings = (new HeadingRowImport)->toArray(file);
插入文件路径代替file关键字。