最近做了个数据导出到excel输出的问题,整个过程比较纠结,现做个简单的回顾总结,以后也方便温故。
常用的方法是先将数据通过gridview或者repeater控件在页面上输出显示后再进行导出,但此方法遇到数据量比较大时在显示的时候就很耗时,而且显示的时候虽然有滚动条,但美观上也好不到哪里去。(此处可能可以考虑使用cache保存数据,然后在显示的时候做成分页的形式从cache中读取少量数据仅供显示,然后再把cache中的数据导出,待实践)
于是考虑采取别的做法,先尝试使用HTMLTable,部分代码为:
HtmlTable table = new HtmlTable();
for (int i = 0; i < 20; i++)
{
HtmlTableRow row = new HtmlTableRow();
for (int j = 0; j < 10; j++)
{
HtmlTableCell cell = new HtmlTableCell();
cell.InnerHtml = i.ToString() + "行" + j.ToString() + "列";
row.Cells.Add(cell);
}
table.Rows.Add(row);
}
Response.Clear();
Response.Buffer = true;
Response.Charset = "utf-8";
Response.AppendHeader("Content-Disposition ", "online;filename=File1.excel");
Response.ContentEncoding = System.Text.Encoding.UTF8;
this.EnableViewState = false;
System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new HtmlTextWriter(oStringWriter);
table.RenderControl(oHtmlTextWriter);
Response.Write(oStringWriter.ToString());//#1
Response.End();
但以上导出的excel没有网格线
public StringBuilder htmlString()
{
StringBuilder str = new StringBuilder();
str.AppendLine("<html xmlns:x='urn:schemas-microsoft-com:office:excel'>");
str.AppendLine("<head>");
str.AppendLine( "<!--[if gte mso 9]><xml>");
str.AppendLine(" <x:ExcelWorkbook>");
str.AppendLine( " <x:ExcelWorksheet>");
str.AppendLine( " <x:Name>工作表标题</x:Name>");
str.AppendLine( " <x:WorksheetOptions>");
str.AppendLine( " <x:Print>");
str.AppendLine( " <x:ValidPrinterInfo />");
str.AppendLine( " </x:Print>");
str.AppendLine( " </x:WorksheetOptions>");
str.AppendLine( " </x:ExcelWorksheet>");
str.AppendLine( " </x:ExcelWorksheets>");
str.AppendLine( " </x:ExcelWorkbook>");
str.AppendLine( " </xml>");
str.Append( "<![endif]-->");
str.AppendLine( "</head>");
str.AppendLine( "<body>");
return str;
}
上述#1处改成:
Response.Write(htmlString().ToString() + oStringWriter.ToString() + "</body></html>");
此方法相当于得到了一个table,只是跳过了页面的显示直接输出成excel,而且经过研究可以发现其仍是将table先转成htmlstring后再导出。