列名となる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;
});
私は正しい解決策が何であるか理解できません。
ありがとう@ 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
)
このコードは私のために働いた:
$results = Excel::selectSheetsByIndex(0)->load($file)->get();
echo "<pre>";
var_dump($results->getHeading());
echo "</pre>";
これを試して:
/**
* @param \SplFileInfo $file
*
* @return Array
*/
public function run(SplFileInfo $file)
{
$excelFile = Excel::load($file);
$excelData = $excelFile->all();
return (($excelData->first())->keys())->toArray();
}
もう少し最適化されたアプローチを共有したかっただけです(これは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();