将Repeater输出为excel

我正试图导出我的中继器到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 

我的代码有什么问题,或者我需要做什么来解决这个问题。 谢谢

您正在将内容types设置为application/vnd.ms-excel但是当您调用RenderContents方法时,您正在响应stream中发送HTML内容。 您可能需要一个库来生成Excel文件。

尝试包装你的内容到这个:

 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>");