Visual Studio 为www.example.com中的Excel工作表给予背景颜色asp.net

a14dhokn  于 2022-11-25  发布在  .NET
关注(0)|答案(4)|浏览(108)

我正在www.example.com中执行导出到excel的操作asp.net但没有使用任何第三方控件。如何为导出的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();
}
atmip9wb

atmip9wb1#

在Excel的HTML定义中似乎有办法,虽然我没有尝试过,请参见http://www.c-sharpcorner.com/UploadFile/kaushikborah28/79Nick08302007171404PM/79Nick.aspx,并在http://msdn.microsoft.com/en-us/library/Aa155477%28office.10%29.aspx处检查官方文档(关于Excel HTML的帮助文件)
创建Excel文件的更好替代方法是使用例如来自Microsoft的OpenXML(免费库),请参见http://msdn.microsoft.com/en-us/office/bb265236http://openxmldeveloper.org/

5jdjgkvh

5jdjgkvh2#

您可以只设置列的项样式吗,如下所示:

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

kulphzqa3#

我看过很多博客,人们想改变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();

yquaqz18

yquaqz184#

//使标题文本加粗

dgrExport.HeaderStyle.Font.Bold = true;
 dgrExport.HeaderStyle.BackColor = Color.Black;                            
 dgrExport.HeaderStyle.ForeColor = Color.White;

相关问题