I have following code that I am using for export to excel of a gridview. I am adding the gridview rows into System.Web.UI.WebControls.Table. Now, I need to apply background color to the header and data rows in the exported excel (There are two header rows).
I tired the following. It is not providing the desired result.
Issues of current solution
One header row does not have background color
Coloring is applied to cells that does not have data (cells “H”, “I”, etc.)
How can we correct it?
Note: I am trying to learn the export feature. So, please don't suggest to use any third party controls. I am just exploring all features of this approach.
I am adding the header grouping to the original gridview using following code.
protected void gvCustomers_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
System.Text.StringBuilder sbNewHeader = new StringBuilder();
sbNewHeader.AppendFormat(" </th>" +
"<th colspan='2' class='tableColGroupAssociate'>Associate Info <a href='#' class='associateHide'> Hide </a> </th>" +
"<th colspan='2' class='tableColGroupTransaction'>Financial Info <a href='#' class='financialHide'> Hide </a> </th>" +
"<th colspan='2' class='tableColGroupDailyTax'>Tax Info <a href='#' class='dailyTaxHide'> Hide </a> </th>"
+ "</tr>");
sbNewHeader.AppendFormat("<tr class='{0}'><th>{1}", this.gvCustomers.HeaderStyle.CssClass, e.Row.Cells[0].Text);
e.Row.Cells[0].Text = sbNewHeader.ToString();
}
}
Complete Code
public static void Export(GridView gv)
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "MyExcelFile.xls"));
HttpContext.Current.Response.ContentType = "application/ms-excel";
using (StringWriter stringWriter = new StringWriter())
{
using (HtmlTextWriter tetxWriter = new HtmlTextWriter(stringWriter))
{
System.Web.UI.WebControls.Table tableControl = new Table();
tableControl.GridLines = gv.GridLines;
//Before the next step - we can remove any controls inside the gridview and replace with literal control
// Add the header row to the table
if (gv.HeaderRow != null)
{
TableRow tableRow = gv.HeaderRow;
tableRow.Style[System.Web.UI.HtmlTextWriterStyle.BackgroundColor] = "Orange";
tableControl.Rows.Add(gv.HeaderRow);
}
// Add each of the data rows to the table
foreach (GridViewRow row in gv.Rows)
{
TableRow tableRow = row;
tableRow.Style[System.Web.UI.HtmlTextWriterStyle.BackgroundColor] = "Yellow";
tableControl.Rows.Add(row);
}
// Render the table into the htmlwriter
tableControl.RenderControl(tetxWriter);
// Render the htmlwriter into the response
HttpContext.Current.Response.Write(stringWriter.ToString());
HttpContext.Current.Response.End();
}
}
}
EDIT
Based on comment from Ankit, I tried the following; still the result is not as expected.
if (gv.HeaderRow != null)
{
TableRow tableRow = gv.HeaderRow;
foreach (TableCell cell in tableRow.Cells)
{
cell.Style[System.Web.UI.HtmlTextWriterStyle.BackgroundColor] = "Orange";
}
tableControl.Rows.Add(gv.HeaderRow);
}
If you want more control over how your excel files are written take a look at ClosedXML
Adding a table is as simple as
var wb = new XLWorkbook();
wb.Worksheets.Add(myDataTable);
wb.SaveAs("MySheet.xlsx");
Using the API you can code like this:
var rngTable = ws.Range("B2:F6");
rngTable.FirstCell().Style
.Font.SetBold()
.Fill.SetBackgroundColor(XLColor.CornflowerBlue)
.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Center);
I figured a way to do it... For the benefit of others I will post it here:
References:
ASP.NET Excel export encoding problem
Other Note: When a new Table is created TableSection can be used to define header
newRow.TableSection = TableRowSection.TableHeader;
CODE
//Changed the logic used for adding dynamic header for HTML rendering:
protected void gvCustomers_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
GridViewRow newHeaderRow = new GridViewRow(-1, -1, DataControlRowType.Header, DataControlRowState.Normal);
TableCell cell1 = new TableHeaderCell();
cell1.ColumnSpan = 1; //e.Row.Cells.Count;
cell1.Text = "";
TableCell cell2 = new TableCell();
cell2.ColumnSpan = 2;
cell2.Text = "One";
TableCell cell3 = new TableCell();
cell3.ColumnSpan = 2;
cell3.Text = "Two";
TableCell cell4 = new TableCell();
cell4.ColumnSpan = 2;
cell4.Text = "Three";
newHeaderRow.Cells.Add(cell1);
newHeaderRow.Cells.Add(cell2);
newHeaderRow.Cells.Add(cell3);
newHeaderRow.Cells.Add(cell4);
((GridView)sender).Controls[0].Controls.AddAt(0, newHeaderRow);
}
if (e.Row.RowType == DataControlRowType.Header)
{
//System.Text.StringBuilder sbNewHeader = new StringBuilder();
//sbNewHeader.AppendFormat(" </th>" +
// "<th colspan='2' class='tableColGroupAssociate'>Associate Info <a href='#' class='associateHide'> Hide </a> </th>" +
// "<th colspan='2' class='tableColGroupTransaction'>Financial Info <a href='#' class='financialHide'> Hide </a> </th>" +
// "<th colspan='2' class='tableColGroupDailyTax'>Tax Info <a href='#' class='dailyTaxHide'> Hide </a> </th>"
// + "</tr>");
//sbNewHeader.AppendFormat("<tr class='{0}'><th>{1}", this.gvCustomers.HeaderStyle.CssClass, e.Row.Cells[0].Text);
//e.Row.Cells[0].Text = sbNewHeader.ToString();
}
}
//Export Logic - Applied similar logic once again
public static void Export(GridView gv)
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "MyExcelFile.xls"));
HttpContext.Current.Response.ContentType = "application/ms-excel";
//Response.ContentEncoding = System.Text.Encoding.Unicode;
//Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());
using (StringWriter stringWriter = new StringWriter())
{
using (HtmlTextWriter tetxWriter = new HtmlTextWriter(stringWriter))
{
System.Web.UI.WebControls.Table tableControl = new Table();
tableControl.GridLines = gv.GridLines;
// Add the header row to the table
if (gv.HeaderRow != null)
{
ReplaceControlForExport(gv.HeaderRow);
#region Dynamic Frrst Header Row
TableRow newRow = new TableRow();
TableCell cell1 = new TableHeaderCell();
cell1.ColumnSpan = 1;
cell1.Text = "";
TableCell cell2 = new TableCell();
cell2.ColumnSpan = 2;
cell2.Text = "One";
TableCell cell3 = new TableCell();
cell3.ColumnSpan = 2;
cell3.Text = "Two";
TableCell cell4 = new TableCell();
cell4.ColumnSpan = 2;
cell4.Text = "Three";
newRow.Cells.Add(cell1);
newRow.Cells.Add(cell2);
newRow.Cells.Add(cell3);
newRow.Cells.Add(cell4);
foreach (TableCell cell in newRow.Cells)
{
cell.Style[System.Web.UI.HtmlTextWriterStyle.BackgroundColor] = "Purple";
}
tableControl.Rows.Add(newRow);
#endregion
TableRow originalHeaderRow = gv.HeaderRow;
foreach (TableCell cell in originalHeaderRow.Cells)
{
cell.Style[System.Web.UI.HtmlTextWriterStyle.BackgroundColor] = "Orange";
}
tableControl.Rows.Add(originalHeaderRow);
}
// Add each of the data rows to the table
foreach (GridViewRow row in gv.Rows)
{
ReplaceControlForExport(row);
TableRow tableRow = row;
foreach (TableCell cell in tableRow.Cells)
{
cell.Style[System.Web.UI.HtmlTextWriterStyle.BackgroundColor] = "Yellow";
}
tableControl.Rows.Add(row);
}
// Render the table into the htmlwriter
tableControl.RenderControl(tetxWriter);
// Render the htmlwriter into the response
HttpContext.Current.Response.Write(stringWriter.ToString());
HttpContext.Current.Response.End();
}
}
}
private static void ReplaceControlForExport(Control mainControlElement)
{
for (int i = 0; i < mainControlElement.Controls.Count; i++)
{
Control currentControl = mainControlElement.Controls[i];
if (currentControl is LinkButton)
{
mainControlElement.Controls.Remove(currentControl);
mainControlElement.Controls.AddAt(i, new LiteralControl((currentControl as LinkButton).Text));
}
else if (currentControl is ImageButton)
{
mainControlElement.Controls.Remove(currentControl);
mainControlElement.Controls.AddAt(i, new LiteralControl((currentControl as ImageButton).AlternateText));
}
else if (currentControl is HyperLink)
{
mainControlElement.Controls.Remove(currentControl);
mainControlElement.Controls.AddAt(i, new LiteralControl((currentControl as HyperLink).Text));
}
else if (currentControl is DropDownList)
{
mainControlElement.Controls.Remove(currentControl);
mainControlElement.Controls.AddAt(i, new LiteralControl((currentControl as DropDownList).SelectedItem.Text));
}
else if (currentControl is CheckBox)
{
mainControlElement.Controls.Remove(currentControl);
mainControlElement.Controls.AddAt(i, new LiteralControl((currentControl as CheckBox).Checked ? "True" : "False"));
}
//Recursive Call
if (currentControl.HasControls())
{
ReplaceControlForExport(currentControl);
}
}
}
Related
i'm creating dynamic checkbox and textbox Control on page Load and i want to get the values of control on button click but we are not able to find out
here is my Dynamic control Code
DataTable dt = new DataTable();
da.Fill(dt);
var Count = dt.Rows.Count;
if (Count > 0)
{
TableHeaderRow thr = new TableHeaderRow();
TableHeaderCell cellheader = new TableHeaderCell();
TableHeaderCell thc = new TableHeaderCell();
TableHeaderCell thcode = new TableHeaderCell();
TableHeaderCell thcReason = new TableHeaderCell();
thc.Text = "Select";
thc.CssClass = "pd";
thcode.Text = "Description";
thcode.CssClass = "pdlbl";
thcReason.Text = "Reason";
thcReason.CssClass = "thcReason";
thr.Cells.Add(thc);
thr.Cells.Add(thcode);
thr.Cells.Add(thcReason);
tbl.Rows.Add(thr);
for (int i = 0; i < Count; i++)
{
TableRow tr = new TableRow();
TableCell tc = new TableCell();
TableCell tc1 = new TableCell();
TableCell tc2 = new TableCell();
CheckBox chk = new CheckBox();
Label lbl = new Label();
TextBox txtBox = new TextBox();
txtBox.ID = "txt" + i.ToString();
txtBox.TextMode = TextBoxMode.MultiLine;
chk.ID = "chk" + i.ToString();
lbl.ID = "lbl" + i.ToString();
lbl.Text = dt.Rows[i]["DESCRIPTION"].ToString();
tc.Controls.Add(chk);
tc.Width = new Unit("5px");
tc.CssClass = "chkcntrl";
tc1.Controls.Add(lbl);
tc1.Width = new Unit("75%");
tc2.Controls.Add(txtBox);
tc2.Width = new Unit("20%");
tr.Cells.Add(tc);
tr.Cells.Add(tc1);
tr.Cells.Add(tc2);
tbl.Rows.Add(tr);
}
tbl.EnableViewState = true;
ViewState["tbl"] = true;
}
after create the control i want to find out the values
my code are below
foreach (TableRow tr in tbl.Controls)
{
string str_Confirmed = string.Empty;
string str_Description = string.Empty;
string str_Reason = string.Empty;
foreach (TableCell tc in tr.Controls)
{
if (tc.Controls[0] is CheckBox)
{
if (((CheckBox)tc.Controls[0]).Checked == true)
{
str_Confirmed = "Y";
}
else
{
str_Confirmed = "N";
}
}
if (tc.Controls[1] is Label)
{
string txt = string.Empty;
str_Description = ((Label)tc.Controls[1]).Text;
}
if (tc.Controls[2] is TextBox)
{
str_Reason = ((TextBox)tc.Controls[2]).Text;
//Response.Write(((TextBox)tc.Controls[0]).Text);
}
}
but when i will execute this code we are getting the Specified argument was out of the range of valid values. Parameter name: index please any one can tell me where am wrong
You have different table cells for each control you are adding.
tc has the checkbox control
tc1 has the label control
EDIT: A few other changes were needed to your code.
You were iterating through, tbl.Controls not tbl.Rows
You were iterating through tr.Controls not tr.Cells
The first table row you add is the header information that has no
controls so added check that controls.count() is greater than 0
Hope this helps
foreach (TableRow tr in tbl.Rows)
{
string str_Confirmed = string.Empty;
string str_Description = string.Empty;
string str_Reason = string.Empty;
foreach (TableCell tc in tr.Cells)
{
if (tc.Controls.Count > 0)
{
if (tc.Controls[0] is CheckBox)
{
if (((CheckBox)tc.Controls[0]).Checked == true)
{
str_Confirmed = "Y";
}
else
{
str_Confirmed = "N";
}
}
else if (tc.Controls[0] is Label)
{
string txt = string.Empty;
str_Description = ((Label)tc.Controls[1]).Text;
}
else if (tc.Controls[0] is TextBox)
{
str_Reason = ((TextBox)tc.Controls[2]).Text;
//Response.Write(((TextBox)tc.Controls[0]).Text);
}
}
}
}
I'm using the below code to export the gridview to excel. When I export the contents are appearing fine with no problems, but I am getting a control label like System.WebControls.UI.Style this in my first cell in A1 cell.
Is there a way to hide this or remove and below is my code.
CS:
protected void Unnamed1_Click(object sender, ImageClickEventArgs e)
{
// ExportToExcel();
if (ViewState["DashboardDetails"] != null)
{
lblError.Text = string.Empty;
lblError.Style.Add("display", "None");
grdHorizontalSeatDashboard.AllowPaging = false;
DataTable dtHorizontalDashboard = (DataTable)ViewState["DashboardDetails"];
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=HorizontalDashboard.xls");
Response.Charset = "utf-8";
Response.ContentType = "application/vnd.ms-excel";
using (StringWriter sw = new StringWriter())
{
HtmlTextWriter hw = new HtmlTextWriter(sw);
grdHorizontalSeatDashboard.AllowPaging = false;
grdHorizontalSeatDashboard.DataSource = (DataTable)ViewState["DashboardDetails"];
grdHorizontalSeatDashboard.DataBind();
grdHorizontalSeatDashboard.HeaderRow.BackColor = Color.White;
//Horizontal Cell
TableCell cell0 = grdHorizontalSeatDashboard.HeaderRow.Cells[0];
cell0.BackColor = ColorTranslator.FromHtml("#9AD6EE");
cell0.Width = grdHorizontalSeatDashboard.HeaderRow.Cells[0].Width;
TableCell cell1 = grdHorizontalSeatDashboard.HeaderRow.Cells[1];
cell1.BackColor = ColorTranslator.FromHtml("#96B060");
cell1.Width = grdHorizontalSeatDashboard.HeaderRow.Cells[1].Width;
TableCell cell2 = grdHorizontalSeatDashboard.HeaderRow.Cells[2];
cell2.BackColor = ColorTranslator.FromHtml("#96B060");
cell2.Width = grdHorizontalSeatDashboard.HeaderRow.Cells[2].Width;
TableCell cell3 = grdHorizontalSeatDashboard.HeaderRow.Cells[3];
cell3.BackColor = ColorTranslator.FromHtml("#96B060");
cell3.Width = Unit.Pixel(100);
TableCell cell4 = grdHorizontalSeatDashboard.HeaderRow.Cells[4];
cell4.BackColor = ColorTranslator.FromHtml("#C57838");
cell4.Width = grdHorizontalSeatDashboard.HeaderRow.Cells[4].Width;
TableCell cell5 = grdHorizontalSeatDashboard.HeaderRow.Cells[5];
cell5.BackColor = ColorTranslator.FromHtml("#C57838");
cell5.Width = grdHorizontalSeatDashboard.HeaderRow.Cells[5].Width;
TableCell cell6 = grdHorizontalSeatDashboard.HeaderRow.Cells[6];
cell6.BackColor = ColorTranslator.FromHtml("#C57838");
cell6.Width = grdHorizontalSeatDashboard.HeaderRow.Cells[6].Width;
// Likely $ Impact & Overall Horizontal Utilization
TableCell cell10 = grdHorizontalSeatDashboard.HeaderRow.Cells[10];
cell10.BackColor = ColorTranslator.FromHtml("#9AD6EE");
cell10.Width = grdHorizontalSeatDashboard.HeaderRow.Cells[10].Width;
TableCell cell11 = grdHorizontalSeatDashboard.HeaderRow.Cells[11];
cell11.BackColor = ColorTranslator.FromHtml("#9AD6EE");
cell11.Width = grdHorizontalSeatDashboard.HeaderRow.Cells[11].Width;
foreach (GridViewRow row in grdHorizontalSeatDashboard.Rows)
{
foreach (TableCell cell in row.Cells)
{
cell.BackColor = row.BackColor;
cell.HorizontalAlign = HorizontalAlign.Center;
cell.CssClass = "textmode";
}
}
foreach (TableCell cell in grdHorizontalSeatDashboard.FooterRow.Cells)
{
cell.BackColor = grdHorizontalSeatDashboard.FooterRow.BackColor;
cell.HorizontalAlign = HorizontalAlign.Center;
}
Style style = new Style();
style.BackColor = Color.White;
Response.Write(style);
grdHorizontalSeatDashboard.RenderControl(hw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
}
}
To hide the first column or the first row (A1), just count the current row/column iteration and intercept the first and hide the A1 cell.
var rowCounter = 0;
var cellCounter = 0;
foreach (GridViewRow row in grdHorizontalSeatDashboard.Rows)
{
foreach (TableCell cell in row.Cells)
{
if (rowCounter == 0 && cellCounter == 0)
{
cell.Text = "";
}
cell.BackColor = row.BackColor;
cell.HorizontalAlign = HorizontalAlign.Center;
cell.CssClass = "textmode";
}
cellCounter = 0;
rowCounter++;
}
I have images displayed from a folder and with the help of the function below i am able to do just that.
private void LoadImages()
{
foreach (string strfile in Directory.GetFiles(Server.MapPath("~/Data")))
{
ImageButton imageButton = new ImageButton();
FileInfo fi = new FileInfo(strfile);
imageButton.ImageUrl = "~/Data/" + fi.Name;
imageButton.Height = Unit.Pixel(100);
imageButton.Style.Add("padding", "5px");
imageButton.Width = Unit.Pixel(100);
imageButton.Click += new ImageClickEventHandler(imageButton_Click);
Panel1.Controls.Add(imageButton);
}
}
Guys! i need to display the name of the image below the image. Help Please!
Wrap the ImageButton into a parent DIV element with the text label. A small table with two rows and 1 cell would work well also.
Example:
Table table = new Table();
TableRow row = new TableRow();
TableCell cell = new TableCell();
table.Controls.Add(row);
row.Controls.Add(cell);
cell.Controls.Add(imageButton);
row = new TableRow();
cell = new TableCell();
table.Controls.Add(row);
row.Controls.Add(cell);
cell.Text = "Image Text";
Im having trouble executing codes after Response.End().
Im using this to export a datatable/ASP Table to MS Excel(.xls).
The export finishes but my Gridview is not loading anymore. The command that I use to load the gridview is written after Response.End().
I tried using HttpContext.Current.ApplicationInstance.CompleteRequest(); but it did not help.
I tried also Response.Redirect("Charges_Trs.aspx", false); still did not work..
Any help please..Here is my code
lblNotif.Text = "Selected items have been posted. Exporting XLS ... (will be saved in your desktop)";
exportToExcel(dt); //calls the function to export the datatable to excel, i passed dt=datatable to this function
timerNotif.Enabled = true;
btnSearch_Click(null, null); //called the event of a button that loads the gridview
here is the function exporttoexcel()
public void exportToExcel(DataTable dt)
{
Table dTable = new Table();
TableRow dTableRow = new TableRow();
//Column Headings
for (int i = 0; i < dt.Columns.Count; i++)
{
TableCell tCell = new TableCell();
tCell.Text = dt.Columns[i].ToString();
dTableRow.Cells.Add(tCell);
}
dTable.Rows.Add(dTableRow);
//Rows
for (int i = 0; i < dt.Rows.Count; i++)
{
dTableRow = new TableRow();
for (int j = 0; j < dt.Columns.Count; j++)
{
TableCell tCell = new TableCell();
dTableRow.Cells.Add(tCell);
}
dTable.Rows.Add(dTableRow);
}
if (Response.IsClientConnected)
{
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=PostedCharges" + DateTime.Now.ToString("MMddyyyy") + ".xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
dTable.RenderControl(hw);
string style = #"<style> .textmode { mso-number-format:\#; } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
}
can u try adding the code in the btnSearch click event(hope it is to bind the grid with some data ) after calling export, instead of calling that click event.
Hi there i have this code to export my data gridview to excel
and my problem is that, the gridview shows a 12hr format but when i export it to excel it shows a 24hr format, how ca i make it into 12 hr format? thank you.
DataSet ds = (DataSet)ViewState["audit"];
DataTable dt = new DataTable();
dt = ds.Tables[0];
Table table = new Table();
AuditTrailGV.AllowPaging = false;
AuditTrailGV.DataSource = (DataSet)ViewState["audit"];
AuditTrailGV.DataBind();
for (int i = 0; i < AuditTrailGV.HeaderRow.Cells.Count; i++)
{
AuditTrailGV.HeaderRow.Cells[i].Style.Add("background-color", "#bfc2c7");
}
AuditTrailGV.HeaderRow.Style.Add("border-color", "#FFFFFF");
int j = 1;
foreach (GridViewRow gvrow in AuditTrailGV.Rows)
{
//gvrow.BackColor = color.White;
gvrow.Style.Add("background-color", "#FFFFFF");
gvrow.Style.Add("border-color", "#bfc2c7");
if (j <= AuditTrailGV.Rows.Count)
{
if (j % 2 != 0)
{
for (int k = 0; k < gvrow.Cells.Count; k++)
{
gvrow.Cells[k].Style.Add("background-color", "#EFF3FB");
gvrow.Cells[k].Style.Add("border-color", "#bfc2c7");
}
}
else
{
for (int k = 0; k < gvrow.Cells.Count; k++)
{
gvrow.Cells[k].Style.Add("border-color", "#bfc2c7");
}
}
}
j++;
}
foreach (GridViewRow row in AuditTrailGV.Rows)
{
table.Rows.Add(row);
}
TableHeaderCell header = new TableHeaderCell();
header.RowSpan = 1;
header.ColumnSpan = 6;
header.Text = "Inventory Accounting and Control System";
header.Font.Bold = true;
header.HorizontalAlign = HorizontalAlign.Center;
header.VerticalAlign = VerticalAlign.Middle;
header.Font.Size = 20;
TableRow headerrow = new TableRow();
headerrow.Cells.Add(header);
TableHeaderCell header2 = new TableHeaderCell();
header2.RowSpan = 1;
header2.ColumnSpan = 6;
header2.Text = "Audit Trail";
header2.Font.Bold = true;
header2.HorizontalAlign = HorizontalAlign.Center;
header2.VerticalAlign = VerticalAlign.Middle;
header2.Font.Size = 16;
TableRow headerrow2 = new TableRow();
headerrow2.Cells.Add(header2);
TableHeaderCell header3 = new TableHeaderCell();
header3.RowSpan = 1;
header3.ColumnSpan = 6;
header3.Text = DatefromTxtBox.Text + " to " + DatetoTxtBox.Text;
header3.Font.Bold = true;
header3.HorizontalAlign = HorizontalAlign.Center;
header3.VerticalAlign = VerticalAlign.Middle;
header3.Font.Size = 16;
TableRow headerrow3 = new TableRow();
headerrow3.Cells.Add(header3);
table.Rows.AddAt(0, headerrow);
table.Rows.AddAt(1, headerrow2);
table.Rows.AddAt(2, headerrow3);
table.Rows.AddAt(3, AuditTrailGV.HeaderRow);
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "IACSAuditTrail" + "[" + DatefromTxtBox.Text.Replace("/", "") + "_" + DatetoTxtBox.Text.Replace("/", "") + "]" + ".xls"));
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
table.RenderControl(htw);
Response.Write(sw.ToString());
Response.End()
This it what it looks
but this is what i looks when i export it to excel :(
The only way to save date format is to pre-format the date field as text and then export to excel. To do this,
string style = #"<style> TD { mso-number-format:\#; } </style> ";
Response.write(style);
//Code to Export Control
Panel1.RenderControl(htmlWrite);
you can refer to below link for more information
http://www.aspsnippets.com/Articles/Export-GridView-To-Word-Excel-PDF-CSV-Formats-in-ASP.Net.aspx