DataGridView To Excel With Colored Cells

前端 未结 2 828
有刺的猬
有刺的猬 2021-01-16 14:38

I looked a lots of example and demo but I could not to it.

I\'m trying to convert datagridview to excel.

My Results http://i.imgur.com/ujvGiXX.png

Bu

相关标签:
2条回答
  • 2021-01-16 15:08

    Try this code for exporting to excel instead of what you are using. I use this for web apps though.

    private void ExportGridToExcel()
    {
        Response.Clear();
        Response.Buffer = true;
        Response.ClearContent();
        Response.ClearHeaders();
        Response.Charset = "";
        string FileName = "SomeFileName" + DateTime.Now + ".xls";
        StringWriter strwritter = new StringWriter();
        HtmlTextWriter htmltextwrtter = new HtmlTextWriter(strwritter);
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.ContentType = "application/vnd.ms-excel";
        Response.AddHeader("Content-Disposition", "attachment;filename=" + FileName);
        GridView1.GridLines = GridLines.Both;
        GridView1.HeaderStyle.Font.Bold = true;
        GridView1.RenderControl(htmltextwrtter);
        Response.Write(strwritter.ToString());
        Response.End();
    }
    public override void VerifyRenderingInServerForm(Control control)
    {
        /* Confirms that an HtmlForm control is rendered for the specified ASP.NET
           server control at run time. */
    }
    
    0 讨论(0)
  • 2021-01-16 15:16

    update the internal loop to be:

    for (i = 0; i <= dataGridView1.RowCount - 2; i++)
                {
                    for (j = 0; j <= dataGridView1.ColumnCount - 1; j++)
                    {
                        Range range = (Range)xlWorkSheet.Cells[i + 1, j + 1];
                        xlWorkSheet.Cells[i + 1, j + 1] = dataGridView1[j, i].Value.ToString();
                        range.Interior.Color = System.Drawing.ColorTranslator.ToOle(dataGridView1.Rows[i].DefaultCellStyle.BackColor );
    
                    }
                }
    

    don't forget:

    using Microsoft.Office.Interop.Excel;
    

    see:
    Change the background of Cells with C#

    0 讨论(0)
提交回复
热议问题