且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

以XLS格式导出文件或将xls文件转换为c#.net中的xlsx格式

更新时间:2022-12-08 15:10:08

你不能在这样的代码中进行转换。 .xlsx文件不仅仅是一个XML文件。它是一个包含大量不同XML文件的.ZIP文件。



您别无选择,只能使用OpenXML SDK重写代码以支持导出.xlsx文件,或者通过使用支持以任一格式导出的第三方库。



如果没有对代码进行大规模的重写,你将无法做到这一点。

I have a code that generate xls file using XML formatting (with styles and coloring in celles). Now with out changing the entire code I need to export the excel to xlsx format. I cant use interop. I can use third party dll but expecting any solution without using the third party dll.

Current code that generate xls file is given below,

StringBuilder xmlStrBuilder = new StringBuilder();
xmlStrBuilder.Append("");
xmlStrBuilder.Append("<?mso-application progid=\"Excel.Sheet\"????>");
xmlStrBuilder.Append("<workbook xmlns="\" hold=" />            xmlStrBuilder.Append(" xmlns:o="\" xmlns:x="\"urn:schemas-microsoft-com:office:excel\"");<br" mode="hold" />            xmlStrBuilder.Append(" xmlns:ss=\"urn:schemas-microsoft-com:office:spreadsheet\"");
xmlStrBuilder.Append(" xmlns:html=\"http://www.w3.org/TR/REC-html40\">");
-------------
-------------
xmlStrBuilder.Append("<worksheet>");

response.Clear();
response.AppendHeader("Content-Type", "application/vnd.ms-excel");
response.AppendHeader("Content-disposition", "attachment; filename=" + fileName);
response.Write(xmlStrBuilder);
response.Flush();
response.End();
excelXml.Length = 0;
excelXml.Capacity = 0;



What I have tried:

I tried to use the third party dll which is not converting the file as expected. Changing the mime type to openxmlformat is not working. Any option to use officeopenxml to convert the file.

You cannot do the conversion in your code like this. A .xlsx file is not just one XML file. It's a .ZIP file containing a bunch of different XML files.

You have no choice but to rewrite the code to support exporting .xlsx files, using the OpenXML SDK, OR by using a third party library that supports exporting in either format.

There is no way you're going to do this without a good sized rewrite of your code.