首页 > 解决方案 > 打开损坏的 .xls 文件

问题描述

我正在使用 ExcelDataReader 读取 .xls 文件并提取数据。但是,由于无效的文件签名异常,我无法打开从外部设备获取的 .xls 文件(我可以使用 Excel 打开它,但它会弹出一个文件格式和扩展名不匹配的信息,如果我想打开无论如何)。

FileStream stream = File.Open(filePath, FileMode.Open, FileAccess.Read);
IExcelDataReader excelReader = ExcelReaderFactory.CreateReader(stream);

我尝试使用 Interop 打开它,但是,无法访问 *** .xls 文件。该文件可能已损坏、位于没有响应的服务器上或只读异常。

Missing missing = Missing.Value;
Application excel = new Application();
Workbook workbook = excel.Workbooks.Open(filePath,
         missing, missing, missing, missing, missing,
         missing, missing, missing, missing, missing,
         missing, missing, missing, XlCorruptLoad.xlRepairFile);

有没有办法修复/恢复/打开/读取那些损坏的文件?

ps 使用 Excel 手动打开并执行SaveAs不是一个选项,因为我需要为数百个文件执行此操作。

十六进制内容

标签: c#.netexcel.net-core

解决方案


https://support.microsoft.com/en-gb/office/file-formats-that-are-supported-in-excel-0943ff2c-6014-4e8d-aaea-b83d51d46247这些文件是 XMLSS 类型(2003 xml)和应赋予 .xml 扩展名。这将阻止 Excel 抱怨内容与名称不匹配,并希望在尝试通过互操作时停止错误。

如果互操作不起作用,您可能会找到一个可以处理 XMLSS 的库,例如https://www.codeproject.com/Articles/8459/XmlSS-NET-Spreadsheet-Component或将其作为 XML 文件读取,然后提取您需要的信息。可能将其作为 DataSet ( da = new DataSet()then ds.ReadXml(path_to_file)) 读取提供了一种处理数据的简单方法


推荐阅读