2016-11-25 77 views
3

我想只得到我的excel第一列將是列名稱。laravel excel獲取標題和maatwebsite

我使用此代碼

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; 
     }); 

我不能理解什麼是正確的解決方案。

回答

1

試試這個:

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

    $excelData = $excelFile->all(); 

    return (($excelData->first())->keys())->toArray(); 
} 
2

謝謝@艾哈邁迪 - zalt

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

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

JSON

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

此代碼爲我工作:

$results = Excel::selectSheetsByIndex(0)->load($file)->get(); 
echo "<pre>"; 
var_dump($results->getHeading()); 
echo "</pre>"; 
相關問題