How to convert xls file to xlsx file using C#?

随声附和 提交于 2019-11-29 13:47:31
j1rjacob

Use Free Spire.XLS dll available via NuGet.

Sample:

Workbook workbook = new Workbook();
workbook.LoadFromFile("Input.xls");
workbook.SaveToFile("Output.xlsx", ExcelVersion.Version2013);

You cannot read xls files with OpenXML.

The solution from Microsoft is to read the xls file with Office Interop (but Interop is not recommended to be used on the server), transfer data from Interop step by step to OpenXML.

Another solution is to use an Excel library like EasyXLS and convert between these two Excel file formats:

ExcelDocument workbook = new ExcelDocument();
workbook.easy_LoadXLSFile("Excel.xls");
workbook.easy_WriteXLSXFile("Excel.xlsx");

Find more information about converting xls to xlsx.

I am not quite sure why you need to convert the file and why you don't just read the xls file, using a different technology then OpenXML, for sure.

XLS is the older Excel file format. XSLX is the newer format stored as OpenXML. XSLX is actually a zip file with the various components stored as files within it. You cannot simply rename the file to get it into the new format. To save the file in XSLX you'll have to save the file into the Excel 2010+ format.

If you're using Excel interop then it is an option on the SaveAs method.

for more info check the function: _Workbook.SaveAs Method

and the property: FileFormat:

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.

msdn info here: https://msdn.microsoft.com/en-us/library/microsoft.office.interop.excel._workbook.saveas(v=office.11).aspx

For reliably reading XLS files you could use ExcelDataReader which is a lightweight and fast library written in C# for reading Microsoft Excel files. It supports the import of Excel files all the way back to version 2.0 of Excel (released in 1987!)

Alternatively you could use a file conversion API like Zamzar. This service has been around for 10+ years, and provides a simple REST API for file conversion - it supports XLS to XLSX conversion. You can use it in C# and it has extra features like allowing you to import and export files to and from Amazon S3, FTP servers etc.

Full disclosure: I'm the lead developer for the Zamzar API.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!