ASP.NET 中
用 DataGrid 的 RenderControl 方法输出到 Excel,是一种常见的办法。其本质是用 html 语法编写 Excel, 表
格用 table 表示。但是默认情形下会发现 Excel 的背景中的网格线(Gridlines) 不显示。用什么选项可以显示网格线呢?搜索了一
下,答案是在 <head /> 中嵌入一段内容指示一些选项即可。
<html xmlns:x="urn:schemas-microsoft-com:office:excel">
<head>
<!--[if gte mso 9]><xml>
<x:ExcelWorkbook>
<x:ExcelWorksheets>
<x:ExcelWorksheet>
<x:Name>工作表标题</x:Name>
<x:WorksheetOptions>
<x:Print>
<x:ValidPrinterInfo />
</x:Print>
</x:WorksheetOptions>
</x:ExcelWorksheet>
</x:ExcelWorksheets>
</x:ExcelWorkbook>
</xml>
<![endif]-->
</head>
<body>
<table border="1">
<tr>
<td>test</td>
<td>test</td>
<td>test</td>
<td>test</td>
</tr>
<tr>
<td>test</td>
<td>test</td>
<td>test</td>
<td>test</td>
</tr>
<tr>
<td>test</td>
<td>test</td>
<td>test</td>
<td>test</td>
</tr>
</table>
</body>
</html>
红色两部分都要添加才行。、
<div id="print1" runat="server"></div>
ToExcel(print1, "dfds");
/// <summary>
/// 导出 Excel 文件
/// </summary>
/// <param name="control">控件名称</param>
/// <param name="fileName">Excel 文件名(不含扩展名)</param>
/// <param name="unformat">是否去除链接格式化串</param>
public static void ToExcel(Control control, string fileName, bool unformat)
{
System.IO.StringWriter tw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
control.RenderControl(hw);
System.Web.HttpResponse Response = System.Web.HttpContext.Current.Response;
Response.Write(control.ToString());
Response.Clear();
Response.Charset = "gb2312";
Response.ContentType = "application/vnd.ms-excel";
Response.AppendHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(fileName) + ".xls");
Response.Write(@"<html xmlns:x='urn:schemas-microsoft-com:office:excel'><head> <!--[if gte mso 9]><xml>
<x:ExcelWorkbook>
<x:ExcelWorksheets>
<x:ExcelWorksheet>
<x:Name>工作表标题</x:Name>
<x:WorksheetOptions>
<x:Print>
<x:ValidPrinterInfo />
</x:Print>
</x:WorksheetOptions>
</x:ExcelWorksheet>
</x:ExcelWorksheets>
</x:ExcelWorkbook>
</xml>
<![endif]--> <META http-equiv='Content-Type' content='text/html; charset=gb2312'></head><body>");
string output = tw.ToString();
if (unformat)
{
output = Regex.Replace(output, @"<\s*/?\s*a[^>]*>", "", RegexOptions.Compiled | RegexOptions.IgnoreCase);
output = Regex.Replace(output, @"<\s*/?\s*img[^>]*>", "", RegexOptions.Compiled | RegexOptions.IgnoreCase);
}
Response.Write(output);
Response.Write("</body></html>");
Response.End();
hw.Close();
hw.Flush();
tw.Close();
tw.Flush();
}