表格用文件流的方式输出为excel。实例代码如下:
![ContractedBlock.gif](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![ExpandedBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
public static void DaochuTalbe(string TableInnerHtml, string filename)
{
StringWriter sw = new StringWriter();
sw.WriteLine(TableInnerHtml);
sw.Close();
System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + filename + ".xls");
System.Web.HttpContext.Current.Response.ContentType = "application/ms-excel";
System.Web.HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF7;
System.Web.HttpContext.Current.Response.Write(sw);
System.Web.HttpContext.Current.Response.End();
}
这种方法的从本质上说并非标准的excel格式,不过把html格式的文件另存为excel的格式,然后用excel打开罢了。
打开后会发现导出的excel无表格线,白白的一片,太难看了。
通过分析excel的格式代码,我尝试在程序里增加带表格线的excel头部代码,结果顺利导出有表格线的excel.
增加的代码如下:
![ContractedBlock.gif](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![ExpandedBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
/// <summary>
/// Excel头部
/// </summary>
/// <returns></returns>
public static string AddExcelHead()
{
StringBuilder sb = new StringBuilder();
sb.Append("<html xmlns:x=\"urn:schemas-microsoft-com:office:excel\">");
sb.Append(" <head>");
sb.Append(" <!--[if gte mso 9]><xml>");
sb.Append("<x:ExcelWorkbook>");
sb.Append("<x:ExcelWorksheets>");
sb.Append("<x:ExcelWorksheet>");
sb.Append("<x:Name></x:Name>");
sb.Append("<x:WorksheetOptions>");
sb.Append("<x:Print>");
sb.Append("<x:ValidPrinterInfo />");
sb.Append(" </x:Print>");
sb.Append("</x:WorksheetOptions>");
sb.Append("</x:ExcelWorksheet>");
sb.Append("</x:ExcelWorksheets>");
sb.Append("</x:ExcelWorkbook>");
sb.Append("</xml>");
sb.Append("<![endif]-->");
sb.Append(" </head>");
sb.Append("<body>");
return sb.ToString();
}
![ContractedBlock.gif](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![ExpandedBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
/// <summary>
/// Excel尾部
/// </summary>
/// <returns></returns>
public static string AddExcelbottom()
{
StringBuilder sb = new StringBuilder();
sb.Append("</body>");
sb.Append("</html>");
return sb.ToString();
}