跳到主要內容

發表文章

目前顯示的是有「PhpSpreadsheet」標籤的文章

PhpSpreadsheet 從 Cell 中取值的注意事項

最近在做一個報名系統,需要開放由 Excel 格式報名表上傳報名資料。這項技術之前已有在別的系統上實作過了,是使用 \PhpOffice\PhpSpreadsheet 套件處理上傳的 Excel 檔案,所以把舊的程式套用過來修改即可。 但是在測試的時候,發現部份欄位取值後的資料有問題,一查原來是 Excel 儲存格(Cell)中有設定格式,此時這個儲存格變成 Richtext Cell,在 PhpSpreadsheet 中用 getValue() 取值時,會取出一堆格式的資訊。 在查閱了一些資料後,似乎沒有一個萬用的取值函數,必須要判斷取出的資料是否為 Richtext,若是 Richtext 格式,需要再用 getPlaintext() 函數去把文字內容取出。 如此,在取出每一個儲存格內容後,都有用一個 if 來判斷取出的資料類型後再處理,真的有夠麻煩。還好這次系統要取的欄位沒有很多,萬一未來遇到很多的資料時,一堆 IF 一定會 keyin 在累死,而且程式執行效率也一定會變慢。 有空再來研究看看,有沒有比較省力的方法吧。

PHP + CI4 的 PhpSpreadsheet 的處理

0、需要用到的 Library use \PhpOffice\PhpSpreadsheet\Spreadsheet; use \PhpOffice\PhpSpreadsheet\Writer\Xlsx; use \PhpOffice\PhpSpreadsheet\Reader\Xlsx; use \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; 參考資料: Welcome to PhpSpreadsheet's documentation - PhpSpreadsheet Documentation  1、上傳 excel 檔案並讀取內容 //處理上傳 try {             $thefile = $this->request->getFile('theuploadfile'); } catch (\Exception $e) { echo $e; exit; } try { $path = $thefile->store(); } catch (\Exception $e) { echo $e; exit; } //確認檔案格式並讀取內容 $filename = WRITEPATH . 'uploads/' . $path; $fileext = ucfirst($thefile->getClientExtension()); if (in_array($fileext, array('Xls', 'Xlsx'))) { $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($fileext); $spreadsheet = $reader->load($filename); $sheet = $spreadsheet->getSheet(0); $data = $sheet->getCell('A1')->getValue(); } 2、產生 Excel 檔案 / /生成試算表並設定格式 $spreadsheet = new Spreadsheet(); $spreadsh...