在asp.net中为Excel工作表指定背景颜色

问题描述 投票:0回答:4

我正在 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();
}
c# asp.net visual-studio export-to-excel
4个回答
0
投票

在Excel的HTML定义中似乎有办法,尽管我没有尝试,请参阅http://www.c-sharpcorner.com/UploadFile/kaushikborah28/79Nick08302007171404PM/79Nick.aspx并检查官方文档(有关 Excel HTML 的帮助文件)位于 http://msdn.microsoft.com/en-us/library/Aa155477%28office.10%29.aspx

创建 Excel 文件的更好替代方法是使用 Microsoft 的 OpenXML(免费库),请参阅 http://msdn.microsoft.com/en-us/office/bb265236http://openxmldeveloper.org/


0
投票

你可以只设置列的项目样式吗,像这样:

GridView1.Columns[0].ItemStyle.BackColor = Color.PeachPuff;
GridView1.Columns[1].ItemStyle.BackColor = Color.Red;

0
投票

我看过很多博客,人们想要更改 Excel 工作表的背景颜色。这是解决方案(工作)。请尝试这个。

下面列出的代码将更改 Excel 工作表的背景和前景色以及导出到 Excel 的任何数据。

    Response.Write("<HTML><HEAD>");
    Response.Write("<style> BODY { background-color:lightyellow; } TD { background-color:lightgrey; } </style>");        
    Response.Write("</HEAD><BODY>");        
    Response.Write(stringWrite.ToString());
    Response.Write("</BODY></HTML>");
    Response.End();

Implemented Code


0
投票

//将标题文本设为粗体

 dgrExport.HeaderStyle.Font.Bold = true;
 dgrExport.HeaderStyle.BackColor = Color.Black;                            
 dgrExport.HeaderStyle.ForeColor = Color.White;
© www.soinside.com 2019 - 2024. All rights reserved.