Format cells column text in excel using c#.net

Format cells column text in excel using c#.net

Hello everyone, I am going to share the code sample for formatting to an excel cells column using c#

Table of content
  1. Connection String for connect DB to bond and display excels.
  2. Example code for format cells column text in excel.

Connection String

string constr = System.Configuration.ConfigurationManager.ConnectionStrings["ConnString"].ToString();

Example code for format cells text in excel

protected void BtnFormatCellsInExcel_Click1(object sender, EventArgs e)
{
        DataTable dt = new DataTable();
        SqlDataReader dataReader;

        SqlConnection conn = new SqlConnection(constr);
        SqlCommand cmd = new SqlCommand("select * from dbo.TableName", conn);

        conn.Open();

        dataReader = cmd.ExecuteReader();
        dt.Load(dataReader);

        conn.Close();

        GrvFormatCellsInExcel.DataSource = dt;
        GrvFormatCellsInExcel.DataBind();

        Response.Clear();
        Response.Buffer = true;

        Response.AddHeader("content-disposition","attachment;filename=GridViewExport.xls");
        Response.Charset = "";
        Response.ContentType = "application/vnd.ms-excel";

        StringWriter stringWriter = new StringWriter();
        HtmlTextWriter htmlTextWriter = new HtmlTextWriter(stringWriter);

        GrvFormatCellsInExcel.AllowPaging = false;
        GrvFormatCellsInExcel.DataBind();
       
        for (int i = 0; i < GridView1.Rows.Count; i++)
        {
            GridViewRow row = GrvFormatCellsInExcel.Rows[i];
            row.BackColor = System.Drawing.Color.Red;
            row.Attributes.Add("Anyclass", "Anytextmode");
        }
        GrvFormatCellsInExcel.RenderControl(htmlTextWriter);
        string style = @"<style> .textmode { mso-number-format:\@; } </style>";
        Response.Write(style);
        Response.Output.Write(stringWriter.ToString());
        Response.Flush();
        Response.End();
    }



ANIL SINGH

Anil Singh is an author, tech blogger, and software programmer. Book writing, tech blogging is something do extra and Anil love doing it. For more detail, kindly refer to this link..
My Blogs - https://code-sample.com and https://code-sample.xyz
My Book1 - BEST SELLING ANGULAR BOOK (INCLUDING ALL VERSIONS 2, 4, 5, 6, 7)
My Book2 - ANGULAR 2 INTERVIEW QUESTIONS BOOK - Both Books are Available on WorldWide.

www.code-sample.com/. Powered by Blogger.