【发布时间】:2011-11-02 14:10:46
【问题描述】:
我在 asp.net 中执行导出到 excel,而不使用任何第三方控件。如何为导出的 Excel 表添加背景颜色?
根据某些单元格范围,背景颜色可能(不确定)不同。从单元格 0-5(excel 中的单元格 A-E)说是红色,6-12 是绿色等等。
我怎样才能达到同样的效果?
public static void DataSetToExcel(System.Data.DataSet dtExport, System.Web.HttpResponse response, string strFileName)
{
//Clean up the response Object
response.Clear();
response.Charset = "";
//Set the respomse MIME type to excel
response.ContentType = "application/vnd.ms-excel";
//Opens the attachment in new window
response.AddHeader("Content-Disposition", "attachment; filename=" + strFileName.ToString() + ".xls;");
response.ContentEncoding = Encoding.Unicode;
response.BinaryWrite(Encoding.Unicode.GetPreamble());
//Create a string writer
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
//Create an htmltextwriter which uses the stringwriter
System.Web.UI.HtmlTextWriter htmlWrite = new System.Web.UI.HtmlTextWriter(stringWrite);
//Instantiate the datagrid
System.Web.UI.WebControls.GridView dgrExport = new System.Web.UI.WebControls.GridView();
//Set input datagrid to dataset table
dgrExport.DataSource = dtExport.Tables[0];
//bind the data with datagrid
dgrExport.DataBind();
//Make header text bold
dgrExport.HeaderStyle.Font.Bold = true;
//bind the modified datagrid
dgrExport.DataBind();
//Tell the datagrid to render itself to our htmltextwriter
dgrExport.RenderControl(htmlWrite);
//Output the HTML
response.Write(stringWrite.ToString());
response.End();
}
【问题讨论】:
-
分享一些代码可能很有用 - 例如,您是在构建 XLS 还是 XLSX 或其他东西。
-
所以您实际上并不是在生成 Excel 文件,而是在生成 HTML 文件(使用虚假的 MIME 类型/文件名来鼓励它加载到 Excel 中)。
-
但最后只能使用打开-保存-取消按钮生成一个excel
-
您可能需要考虑改为在相关的 Open XML 标准中生成文件(有 some information on MSDN)
-
所以不可能给背景颜色相同的颜色?
标签: c# asp.net visual-studio export-to-excel