Excel/CSV 匯入匯出庫,支援大檔案,樣式設定,單元格合併

馨竹之鄉發表於2020-03-30

前言

  • 專案上使用過maatwebsite/Excel, mk-j/php_xlsxwriter, box/spout這三個庫,簡單說下使用體驗
  • maatwebsite/Excel 優點功能非常強大,不足的是佔用記憶體太多,對於匯出大檔案無法滿足需求
  • mk-j/php_xlsxwriter 優點支援大檔案寫入,常規樣式設定,不足的是僅支援excel匯出,不支援匯入,也不支援csv的匯入/匯出
  • box/spout 優點是支援大檔案,支援excel/csv匯入/匯出,不足的是不支援單元格合併

環境要求

  • PHP version 7.1 or higher
  • PHP extension php_zip enabled
  • PHP extension php_xmlreader enabledR

##安裝

匯出

include "./vendor/autoload.php";

$writer = \Rocky114\Excel\Writer\WriterFactory::createXLSXWriter();
$writer->setTempFolder('.');

$writer->addNewSheet('sheet1');

$type = ['A' => 'string', 'B' => '#,##0'];
$writer->addHeader(['name', 'id'], $type)
->addRow(['xinzhu', 1234565])>addRow(['rocky', 21])->save();

匯入

include "./vendor/autoload.php";

$reader = \Rocky114\Spreadsheet\ReaderFactory::createReaderFromFile('./test.xlsx');

$data = [];
foreach ($reader->getSheetIterator() as $sheet) {
     foreach ($sheet->getRowIterator() as $row) { 
        $data[] = $row; 
     }
}

// or
$data = $reader->getSheet()->load();
本作品採用《CC 協議》,轉載必須註明作者和本文連結

馨竹

相關文章