我有一个HTML表格(不是GridView),它没有适当的标题和行。相反,它具有自定义的结构和数据。我想使用ASP.NET将此表导出到Excel。我该怎么做?
标签是固定文本,整数值来自数据库。因此,表格结构是固定的,只有整数/小数值会更改。
Provide the ID
and add runat="server"
attribute
<table id="tbl" runat="server" >
Add the following code
Response.ContentType = "application/x-msexcel";
Response.AddHeader("Content-Disposition", "attachment;
filename=ExcelFile.xls");
Response.ContentEncoding = Encoding.UTF8;
StringWriter tw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(tw);
tbl.RenderControl(hw);
Response.Write(tw.ToString());
Response.End();
Response
给了我一个错误。 - SearchForKnowledgeResponse.ContentType = "application/force-download";
Response.AddHeader("content-disposition", "attachment; filename=Print.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]--> ");
StringWriter tw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(tw);
tbl.RenderControl(hw);
Response.Write(tw.ToString());
Response.Write("</head>");
Response.flush();
如果您希望导出的内容与您的UI界面完全一致,建议您提供内联CSS样式。如果将CSS类应用于表格,则不会在导出的Excel中显示。
if (dtReports != null && dtReports.Rows.Count > 0 && !string.IsNullOrEmpty(formName))
{
string filename = formName.ToUpper() + ParsConstant.XLS_EXTENSION;
StringWriter tw = new StringWriter();
using (HtmlTextWriter hw = new HtmlTextWriter(tw))
{
//Binding Datatable to DataGrid.
DataGrid dgGrid = new DataGrid();
dgGrid.DataSource = dtReports;
dgGrid.DataBind();
//Some Properties for the Header
dgGrid.HeaderStyle.Font.Bold = true;
dgGrid.HeaderStyle.Font.Size = 13;
//Get the HTML for the control.
dgGrid.RenderControl(hw);
Response.ContentType = "application/vnd.ms-excel";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + "");
//Response.Write("<style> TD { mso-number-format:\\@; } </style>");
Response.Write(tw.ToString());
Response.End();
}
}
没有自动化的方法。但是你可以使用相同的代码创建表格并将其写入输出中。如果以简单的 CSV 文件形式编写它,那么用户只需点击下载的文件即可将其加载到 Excel 中。
通过设置正确的标头,您可以指示浏览器将内容视为下载而不是网页。我在this article中发布了执行此操作的代码。