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

Hey! I'm Anil Singh. I author this blog. I'm Active Blogger, Programmer. I love learning new technologies, programming, blogging and participating the forum discussions more...
http://www.code-sample.com
http://www.code-sample.xyz

You Might Also Like
Post a Comment
www.code-sample.com/. Powered by Blogger.