Hello everyone, I
am going to share the code sample for formatting to an
excel cells column using c#.
Table of content
- Connection String for connect DB to bond and display excels.
- 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();
}