c# - 打开损坏的 .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不是一个选项,因为我需要为数百个文件执行此操作。
解决方案
从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)
) 读取提供了一种处理数据的简单方法
推荐阅读
- javascript - 如何在同一行获得 4 张卡目前我连续有 2 张卡
- java - 使用单个 UDP 套接字从 Java 中的不同线程读取/写入是否安全
- angular - Cloudinary 的上传小部件 v2 中的多个文件问题
- r - 如何按填充颜色对 ggplot2 中的条形图进行分组,同时保持降序?
- php - UNISERVER 严格表
- php - 错误:您的要求无法解析为一组可安装的软件包
- github - 有没有办法自动要求 PR 作者从分支/叉子中删除文件夹?
- selenium-webdriver - 无法使用 setFillBackgroundColor + apache poi 为 excel 单元格着色
- flutter - Flutter浮动按钮隐藏和显示ListView是否索引
- r - 如何将盒须图上的四分位数值带入序数尺度,以用作序数逻辑回归中的因变量?