我正在开发一个从excel文件中读取数据的应用程序,但是当我尝试打开源文件时,如果该文件采用xls格式保存,则会抛出异常(使用OpenXML打开Excel工作表时文件包含损坏的数据错误)。实际上,当我将此文件以xlsx格式保存时,它可以正常工作。请帮我解决这个问题。
使用通过NuGet提供的免费Spire.XLS dll。
示例:
Workbook workbook = new Workbook();
workbook.LoadFromFile("Input.xls");
workbook.SaveToFile("Output.xlsx", ExcelVersion.Version2013);
使用OpenXML无法读取xls文件。
微软的解决方案是使用Office Interop来读取xls文件(但不建议在服务器上使用Interop),逐步将数据从Interop转移到OpenXML。
另一种解决方案是使用类似于EasyXLS的Excel库来在这两种Excel文件格式之间进行转换:
ExcelDocument workbook = new ExcelDocument();
workbook.easy_LoadXLSFile("Excel.xls");
workbook.easy_WriteXLSXFile("Excel.xlsx");
了解更多关于将xls转换为xlsx的信息。
我不太确定为什么您需要转换文件,而不是使用其他技术读取xls文件,肯定不是OpenXML。
Optional Object.
The file format to use when you save the file. For a list of valid choices,
see the FileFormat property. For an existing file, the default format is the
last file format specified; for a new file, the default is the format of the
version of Excel being used.