在没有Interop或库的情况下从asp listview创buildexcel文件

我想创build一个基于我的asp ListView的Excel文件,但我不能使用互操作,因为服务器没有安装Microsoft套件。 我也想避免使用外部库。

这是我在互联网上find的一些代码的一部分,但它没有看到工作。

public void Export(string fileName, List<string> liste) { HttpContext.Current.Response.Clear(); HttpContext.Current.Response.AddHeader( "content-disposition", string.Format("attachment; filename={0}", fileName + ".xls")); HttpContext.Current.Response.ContentType = "application/ms-excel"; using (StringWriter sw = new StringWriter()) { using (HtmlTextWriter htw = new HtmlTextWriter(sw)) { lvOutput.RenderControl(htw); HttpContext.Current.Response.Write(sw.ToString()); HttpContext.Current.Response.End(); } } } 

这里是html项目模板,它基本上是一个我分成4列的string。

 <ItemTemplate> <tr> <td class="col-md-3"> <asp:Label ID="lbl1" runat="server" Text="<%# Container.DataItem.ToString().Split(';')[0] %>" /> </td> <td class="col-md-3"> <asp:Label ID="lbl2" runat="server" Text="<%# Container.DataItem.ToString().Split(';')[1] %>" /> </td> <td class="col-md-3"> <asp:Label ID="Label1" runat="server" Text="<%# Container.DataItem.ToString().Split(';')[2] %>" /> </td> <td class="col-md-3"> <asp:Label ID="Label2" runat="server" Text="<%# Container.DataItem.ToString().Split(';')[3] %>" /> </td> </tr> </ItemTemplate> 

这将让你的Excel文件。 我无法专门testingRenderControl,因为您没有提供布局。 看看这是否工作,并更新我。

 Response.ContentType = "application/force-download"; Response.AddHeader("content-disposition", "attachment; filename=ExcelSheet.xls"); Response.Write("<html xmlns:x=\"urn:schemas-microsoft-com:office:excel\">"); Response.Write("<head>"); Response.Write("<META http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">"); Response.Write("<!--[if gte mso 9]><xml>"); Response.Write("<x:ExcelWorkbook>"); Response.Write("<x:ExcelWorksheets>"); Response.Write("<x:ExcelWorksheet>"); Response.Write("<x:Name>Report Data</x:Name>"); Response.Write("<x:WorksheetOptions>"); Response.Write("<x:Print>"); Response.Write("<x:ValidPrinterInfo/>"); Response.Write("</x:Print>"); Response.Write("</x:WorksheetOptions>"); Response.Write("</x:ExcelWorksheet>"); Response.Write("</x:ExcelWorksheets>"); Response.Write("</x:ExcelWorkbook>"); Response.Write("</xml>"); Response.Write("<![endif]--> "); Response.Write(sw.ToString()); //insert html string Response.Write("</head>"); Response.Flush(); 

资源

编辑 :另外.. Excel文件应该加载得很好,但如果您在Microsoft Excel格式错误,您将希望首先检查您的控件呈现,并确保HTMLstring是正确的。

我知道你想避免使用外部库,但实际上,你的代码不会生成Excel文件。 你只是发送HTML给浏览器一个特定的内容types,希望用户在他/她的机器上有Excel(你不知道他们是否真的这样做)。

由于Excel将为您处理HTML,因此您也放弃了对格式的很多控制。

我强烈build议你不要这样做,而应该使用一个库,比如被许多人广泛使用和testing的ClosedXML 。