解決開啟 Excel 檔案內容錯誤需要復原、移除部分公式的問題

開啟 Excel 檔案時遇到內容有問題,需要復原的問題。可能原因是原始欄位值包含 = 符號,但是並不是函式(例如 === 分隔線 ===)。解決方式:將欄位值前加上單引號。如果要產生 CSV 檔案再轉成 Excel 檔案,則需要將欄位值前後加上雙引號 " 框住欄位值。

Photo by Marc Chouinard from StockSnap

問題狀況

Excel 檔案是透過程式產生檔案,但是開啟檔案時遇到「我們發現 xxx.xlsc 的部分內容有問題。您要我們盡可能嘗試復原嗎?」的訊息文字。有時候 Excel 可以修復又時候不行修復,即使完成修復,也不清楚哪個儲存格資料出現問題。

開啟修復記錄檔,顯示「已移除的記錄: /xl/worksheets/sheet1.xml 部分的 公式」代表工作表1 部分內容的公式已經被移除

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>

<recoveryLog xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><logFileName>檔案名稱.xml</logFileName><summary>檔案 '檔案名稱.xlsx' 中偵測出錯誤</summary><removedRecords summary="下列是已移除記錄的清單:"><removedRecord>已移除的記錄: /xl/worksheets/sheet1.xml 部分的 公式</removedRecord></removedRecords><repairedRecords summary="下列是修復清單:"><repairedRecord>已修復的記錄: /xl/workbook.xml 部分的 工作表內容 (活頁簿)</repairedRecord></repairedRecords></recoveryLog>

解決方法

與 解決打開 Excel 檔案遇到「已移除的記錄: /xl/worksheets/sheet1.xml 部分的公式」 狀況一樣,由於欄位值內容包含由使用者書寫的文章內容,但是並不是函式(例如 === 分隔線 ===),所以需要將 Excel 欄位值前面加上單引號,避免誤以為是公式 (formula)。

如果要產生 CSV 檔案再轉成 Excel 檔案,則需要將欄位值前後加上雙引號 " 框住欄位值。不過如果欄位值包含雙引號,則需要額外 escape,變成 ""。

參考資料

無效的嘗試

附錄

如果使用 PhpSpreadsheet 產生 Excel 檔案,欄位值沒有額外處理會出現以下錯誤:

PHP Fatal error:  Uncaught PhpOffice\PhpSpreadsheet\Calculation\Exception: Worksheet!A2 -> Formula Error: An unexpected error occurred in /Users/excel-test/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/Cell.php:272
Stack trace:
#0 /Users/excel-test/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Worksheet.php(1120): PhpOffice\PhpSpreadsheet\Cell\Cell->getCalculatedValue()
#1 /Users/excel-test/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Worksheet.php(1190): PhpOffice\PhpSpreadsheet\Writer\Xlsx\Worksheet->writeCellFormula(Object(PhpOffice\PhpSpreadsheet\Shared\XMLWriter), '=Hello World !', Object(PhpOffice\PhpSpreadsheet\Cell\Cell))
#2 /Users/excel-test/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Worksheet.php(1047): PhpOffice\PhpSpreadsheet\Writer\Xlsx\Worksheet->writeCell(Object(PhpOffice\PhpSpreadsheet\Shared\XMLWriter), Object(PhpOffice\PhpSpreadsheet\Worksheet\Worksheet), 'A2', Array)
#3 /Us in /Users/excel-test/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/Cell.php on line 272

留言