{"record":{"id":"c077c05db2eef740","repo":"Uahh/ToastFish","slug":"ex-message-excel-read-error","errorCode":null,"errorMessage":"ex.Message, \"Excel read error\"","messagePattern":"ex\\.Message, \"Excel read error\"","errorType":"console","errorClass":null,"httpStatus":null,"severity":"error","filePath":"Model/Log/CreateLog.cs","lineNumber":122,"sourceCode":"                // Try to read WorkBook as XLSX:\n                try\n                {\n                    WorkBook = new XSSFWorkbook(fs);\n                }\n                catch\n                {\n                    WorkBook = null;\n                }\n\n                // If reading fails, try to read WorkBook as XLS:\n                if (WorkBook == null)\n                {\n                    WorkBook = new HSSFWorkbook(fs);\n                }\n            }\n            catch (Exception ex)\n            {\n                MessageBox.Show(ex.Message, \"Excel read error\", MessageBoxButton.OK, MessageBoxImage.Error);\n                return WordList;\n            }\n\n            ISheet Sheet = WorkBook.GetSheetAt(0);\n            IRow FirstRow = Sheet.GetRow(0);\n            if(FirstRow.GetCell(0).ToString() == \"英语\")\n            {\n                int RowCount = Sheet.LastRowNum;\n                for (int i = 1; i <= RowCount; i++)\n                {\n                    IRow Row = Sheet.GetRow(i);\n                    Word TempWord = new Word();\n                    if (Row == null)\n                        continue;\n                    TempWord.headWord = Row.GetCell(1).ToString();\n                    TempWord.tranCN = Row.GetCell(2).ToString();\n                    TempWord.ukPhone = Row.GetCell(3).ToString();\n                    TempWord.usPhone = Row.GetCell(4).ToString();","sourceCodeStart":104,"sourceCodeEnd":140,"githubUrl":"https://github.com/Uahh/ToastFish/blob/2508784a6650862a60e1f3ec3a54dd83efdec98b/Model/Log/CreateLog.cs#L104-L140","documentation":"ImportExcel wraps workbook opening in try/catch and, when neither XSSFWorkbook nor HSSFWorkbook can parse the file, shows a modal 'Excel read error' dialog with the raw exception message. It means the file at `path` could not be opened as either OOXML (.xlsx) or legacy BIFF (.xls) format. The method then returns an empty List<Word> instead of the expected word list.","triggerScenarios":"CreateLog.ImportExcel(path) is called with a file that is not a real Excel workbook: a renamed file, an HTML/CSV file exported as .xls, a password-protected or corrupted workbook, or a file locked/zero bytes. The XSSF parse fails silently, the HSSF fallback throws, and the catch shows the dialog.","commonSituations":"Users rename .csv or .html exports to .xlsx/.xls; files downloaded incompletely; OneDrive/网络 disks handing out placeholder files; Excel files saved in formats NPOI cannot read (e.g. .xlsb, encrypted workbooks); the FileStream itself throws because another process holds an incompatible lock.","solutions":["Open the file in Microsoft Excel/LibreOffice and re-save it as a genuine .xlsx (or .xls) file","Verify the file extension matches the actual format (open the first bytes; .xlsx is a ZIP starting with PK)","Ensure the file is fully downloaded/copied and not zero-length or locked by another process","Wrap the ImportExcel call and check the returned list count; treat an empty list as 'import failed' rather than 'no words'"],"exampleFix":"// before\nobject lstObj = Log.ImportExcel(FileName);\nstring typeObj = lstObj.ToString();\n// after\nvar lstObj = Log.ImportExcel(FileName);\nif (lstObj == null || lstObj.Count == 0)\n{\n    MessageBox.Show(\"File could not be read as xlsx/xls. Re-save it as a real Excel workbook.\");\n    return;\n}","handlingStrategy":"validation","validationCode":"var fi = new FileInfo(path);\nif (!fi.Exists || fi.Length < 512) throw new InvalidDataException(\"不是有效的Excel文件\");\nusing (var peek = File.OpenRead(path)) { int b0 = peek.ReadByte(); int b1 = peek.ReadByte();\n    if (b0 != 'P' && b0 != 0xD0) throw new InvalidDataException(\"文件不是 xlsx (ZIP) 或 xls (OLE) 格式\"); }","typeGuard":"static bool LooksLikeExcel(string path) { try { var b = File.ReadAllBytes(path).Take(8).ToArray();\n    return b.Length >= 4 && (b[0]==0x50 && b[1]==0x4B) || (b[0]==0xD0 && b[1]==0xCF); } catch { return false; } }","tryCatchPattern":"try { var list = Log.ImportExcel(path); }\ncatch (Exception ex) { MessageBox.Show($\"Excel读取失败：{ex.Message}\"); }\nfinally { /* treat empty list as failure */ }","preventionTips":["Always re-save exports from other tools as real .xlsx before importing","Check file size > 0 and magic bytes (PK for xlsx, D0 CF 11 E0 for xls) before import","Keep the extension and actual format consistent","Avoid importing files directly from network/OneDrive placeholders; copy locally first"],"tags":["csharp","npoi","excel","file-read","import"],"backgroundTag":"file-read-failed","analyzedSha":"2508784a6650862a60e1f3ec3a54dd83efdec98b","analyzedAt":"2026-09-15T23:21:32.897Z","contentChangedAt":"2026-09-15T23:21:32.897Z","schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}