我正在尝试将我的转发器导出到excel,这是我的代码......
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
string attachment = "attachment; filename=file.xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/vnd.ms-excel";
rpt.RenderControl(htw);
Response.Write(sw.ToString());
Response.Flush();
Response.End();
当我尝试打开文件时收到此错误
The file you are trying to open, 'file.xls', is in a different format than specified
by the file extension. Verify that the file is not Corrupted and is from a trusted
source before opening the file. Do you want to open the file now?
Yes No Help option are available
我的代码中出现了什么问题或我需要做什么来解决此问题。 感谢
答案 0 :(得分:2)
您正在将内容类型设置为application/vnd.ms-excel
,但在调用RenderContents
方法时,您将在响应流中发送HTML内容。您可能需要一个库来生成Excel文件。
答案 1 :(得分:0)
尝试将您的内容包装成:
StringBuilder sb = new StringBuilder("");
sb.Append("<HTML xmlns:x=\"urn:schemas-microsoft-com:office:excel\"><HEAD>");
sb.Append("<meta http-equiv=Content-Type content=\"text/html; charset=utf-8\">");
sb.Append("<!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>");
sb.Append(title);
sb.Append("</x:Name><x:WorksheetOptions><x:Print><x:ValidPrinterInfo/></x:Print></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--> </HEAD><BODY>");
sb.Append(content);
sb.Append("</BODY></HTML>");