how to remove &nbsp in asp.net excel export - c#

In asp.net Gridview has an empty cell, so when i export it to excel i get &nbsp in that empty cell.
I want to replace that with a blank space.
How do i do it?
Here is my GridView :
<asp:GridView Width="800px" ID="MyGridView" DataSourceID="DataSource1" AutoGenerateColumns="False"
runat="Server" BorderColor="#555555" HorizontalAlign="Center" OnRowDataBound="MyGridView_RowDataBound"
Font-Names="Verdana" Font-Size="12px" AllowSorting="True"
EmptyDataRowStyle-Font-Bold="true" EmptyDataRowStyle-ForeColor="#CC0000">
<EmptyDataTemplate>*** No data available ***</EmptyDataTemplate>
<Columns>
<asp:BoundField HeaderText="COLLEGE" DataField="COLLEGE" ItemStyle-HorizontalAlign="Left" HeaderStyle-BackColor="#CC0000" HeaderStyle-ForeColor="#FFFFFF"
ReadOnly="true" DataFormatString="{0:N0}"/>
<asp:BoundField HeaderText="COLLEGE NAME" DataField="COLLEGE DESC" ItemStyle-HorizontalAlign="Left" HeaderStyle-BackColor="#CC0000" HeaderStyle-ForeColor="#FFFFFF"
ReadOnly="true" DataFormatString="{0:N0}"/>
<asp:BoundField HeaderText="UNDERGRAD" DataField="UNDERGRADUATE" ItemStyle-HorizontalAlign="Right" HeaderStyle-ForeColor="#FFFFFF"
HeaderStyle-BackColor="#CC0000" ReadOnly="true" DataFormatString="{0:N0}"/>
<asp:BoundField HeaderText="GRAD" DataField="GRADUATE" ItemStyle-HorizontalAlign="Right" HeaderStyle-ForeColor="#FFFFFF"
HeaderStyle-BackColor="#CC0000" ReadOnly="true" DataFormatString="{0:N0}"/>
<asp:BoundField HeaderText="LAW" DataField="LAW" ItemStyle-HorizontalAlign="Right" HeaderStyle-ForeColor="#FFFFFF"
HeaderStyle-BackColor="#CC0000" ReadOnly="true" DataFormatString="{0:N0}"/>
<asp:BoundField HeaderText="TOTAL" DataField="TOTAL" ItemStyle-HorizontalAlign="Right" HeaderStyle-ForeColor="#FFFFFF"
HeaderStyle-BackColor="#CC0000" ReadOnly="true" DataFormatString="{0:N0}"/>
</Columns>
</asp:GridView>
Here is my excel export :
public void ExpToExcel_Click(object sender, EventArgs e)
{
MyGridView.DataBind();
MyGridView.AllowPaging = false;
MyGridView.ShowHeader = true;
DataTable dt = new DataTable("GridView_Data");
foreach (TableCell cell in MyGridView.HeaderRow.Cells)
{
dt.Columns.Add(cell.Text);
}
int cellcount = MyGridView.Rows[0].Cells.Count;
foreach (GridViewRow row in MyGridView.Rows)
{
DataRow datarw;
datarw = dt.NewRow();
for (int i = 0; i < cellcount; i++)
{
datarw[i] = row.Cells[i].Text;
}
dt.Rows.Add(datarw);
}
ExcelPackage excel = new ExcelPackage();
var workSheet = excel.Workbook.Worksheets.Add("Sheet1");
workSheet.Cells["J1"].Value = "TEXAS TECH UNIVERSITY";
workSheet.Cells["J1"].Style.Font.Size = 24;
workSheet.Cells["J1"].Style.Font.Bold = true;
workSheet.Cells["I2"].Value = "DEPARTMENT OF INSTITUTIONAL RESEARCH";
workSheet.Cells["I2"].Style.Font.Size = 20;
workSheet.Cells["I2"].Style.Font.Bold = true;
workSheet.Cells["J3"].Value = caption.Text.ToUpper();
workSheet.Cells["J3"].Style.Font.Bold = true;
workSheet.Cells["L4"].Value = "(UnCertified Data)";
workSheet.Cells["A7:F7"].Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
workSheet.Cells["A7:F7"].Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.Red);
workSheet.Cells["A7:F7"].Style.Font.Color.SetColor(System.Drawing.Color.White);
workSheet.Cells["A21:F21"].Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
workSheet.Cells["A21:F21"].Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.Red);
workSheet.Cells["A21:F21"].Style.Font.Color.SetColor(System.Drawing.Color.White);
workSheet.Cells[7, 1].LoadFromDataTable(dt, true);
workSheet.Cells["A7:F7"].AutoFitColumns();
using (var memoryStream = new MemoryStream())
{
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment; filename=Enrollment_Major_Classification.xlsx");
excel.SaveAs(memoryStream);
memoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.End();
}
}
So in the college name column i get &nbsp which i want to remove.
I tried using TRIM but did not work.
Any other suggestions?

I see that you're recreating the styling from the GridView into your Excel file, this requires that when you change the GridView styling you must change the code for Excel file as well.
You could avoid this by creating an Excel file from the GridView's HTML representation, for example see the following:
protected void ExpToExcel_Click(object sender, EventArgs e)
{
// Get MyGridView control's HTML representation.
var plainWriter = new StringWriter();
var htmlWriter = new HtmlTextWriter(plainWriter);
this.MyGridView.RenderControl(htmlWriter);
// Load HTML into ExcelFile.
SpreadsheetInfo.SetLicense("FREE-LIMITED-KEY");
var htmlOptions = new HtmlLoadOptions();
var htmlStream = new MemoryStream(htmlOptions.Encoding.GetBytes(plainWriter.ToString()));
var excel = ExcelFile.Load(htmlStream, htmlOptions);
// Download ExcelFile to current HttpResponse.
excel.Save(this.Response, "Enrollment_Major_Classification.xlsx");
}
public override void VerifyRenderingInServerForm(Control control)
{
/* We're overriding this verification because of the "MyGridView.RenderControl" call.
* This confirms that the "HtmlForm" control is rendered for "MyGridView" at run time. */
}
Note, the code uses GemBox.Spreadsheet library.
The following is the result:
This way any change on GridView will be reflected in Excel file as well, without changing the code. As an FYI, I've taken the code from this article.

You should bind your data to a DataTable (as suggested by Scott Hannen)
Here is a fully working example based on your former code
I've also updated the gridview aspx definition (footertext) and also, rowdatabound event
public partial class WebForm2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
MyGridView.DataSource = LoadData();
MyGridView.DataBind();
}
private DataTable LoadData()
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[6] { new DataColumn("COLLEGE", typeof(string)),
new DataColumn("COLLEGE DESC", typeof(string)),
new DataColumn("UNDERGRADUATE",typeof(double)),
new DataColumn("GRADUATE",typeof(double)),
new DataColumn("LAW",typeof(double)),
new DataColumn("TOTAL",typeof(double)),
});
dt.Rows.Add("AG", "College of Ag Sci and", 1902, 401, 0, 2303);
dt.Rows.Add("AR", "College of Architecture", 510, 89, 0, 599);
dt.Rows.Add("AS", "Coll of Arts and Science", 9558, 1281, 0, 10839);
dt.Rows.Add("BA", "Rawls Coll of Business", 4042, 574, 0, 4616);
dt.Rows.Add("ED", "College of Education", 823, 1373, 0, 2196);
dt.Rows.Add("EN", "College of Engineering", 4912, 826, 0, 5738);
dt.Rows.Add("GR", "Graduate School", 0, 254, 0, 254);
dt.Rows.Add("HR", "Honors College", 22, 0, 0, 22);
dt.Rows.Add("HS", "College of Human ...", 2813, 464, 0, 3277);
dt.Rows.Add("LW", "School of Law", 0, 0, 445, 445);
dt.Rows.Add("MC", "Coll of Media and ...", 1855, 232, 0, 2087);
dt.Rows.Add("UN", "Texas Tech University", 3497, 4, 0, 3501);
dt.Rows.Add("VP", "Coll of Visual and", 803, 316, 0, 1119);
return dt;
}
protected void Export_Click(object sender, EventArgs e)
{
using (ExcelPackage excel = new ExcelPackage())
{
var workSheet = excel.Workbook.Worksheets.Add("Sheet1");
workSheet.Cells["J1"].Value = "TEXAS TECH UNIVERSITY";
workSheet.Cells["J1"].Style.Font.Size = 24;
workSheet.Cells["J1"].Style.Font.Bold = true;
workSheet.Cells["I2"].Value = "DEPARTMENT OF INSTITUTIONAL RESEARCH";
workSheet.Cells["I2"].Style.Font.Size = 20;
workSheet.Cells["I2"].Style.Font.Bold = true;
workSheet.Cells["J3"].Value = "test".ToUpper();
workSheet.Cells["J3"].Style.Font.Bold = true;
workSheet.Cells["L4"].Value = "(UnCertified Data)";
workSheet.Cells["A7:F7"].Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
workSheet.Cells["A7:F7"].Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.Red);
workSheet.Cells["A7:F7"].Style.Font.Color.SetColor(System.Drawing.Color.White);
workSheet.Cells["A21:F21"].Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
workSheet.Cells["A21:F21"].Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.Red);
workSheet.Cells["A21:F21"].Style.Font.Color.SetColor(System.Drawing.Color.White);
var dt = MyGridView.DataSource as DataTable;
// add total row to datatable for excel export because rowdatabound event which already calculates total doesn't make total as a part of the datatable at this time
double totalUnderG = 0;
double totalGrad = 0;
double totalLaw = 0;
double total = 0;
foreach (var r in dt.Rows.Cast<DataRow>())
{
totalUnderG += double.Parse(r[2].ToString());
totalGrad += double.Parse(r[3].ToString());
totalLaw += double.Parse(r[4].ToString());
total += double.Parse(r[5].ToString());
}
dt.Rows.Add("TTU TOTAL", "", totalUnderG, totalGrad, totalLaw, total);
workSheet.Cells[7, 1].LoadFromDataTable(dt, true);
workSheet.Cells["A7:F7"].AutoFitColumns();
using (var memoryStream = new MemoryStream())
{
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment; filename=Enrollment_Major_Classification.xlsx");
excel.SaveAs(memoryStream);
memoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.End();
}
}
}
// Declare variable used to store value of Total
double totalUnderG = 0;
double totalGrad = 0;
double totalLaw = 0;
double total = 0;
/// <summary>
/// calculates total when displaying gridview
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void MyGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
// check row type
if (e.Row.RowType == DataControlRowType.DataRow)
{
totalUnderG += Convert.ToDouble(DataBinder.Eval(e.Row.DataItem, "UNDERGRADUATE"));
totalGrad += Convert.ToDouble(DataBinder.Eval(e.Row.DataItem, "GRADUATE"));
totalLaw += Convert.ToDouble(DataBinder.Eval(e.Row.DataItem, "LAW"));
total += Convert.ToDouble(DataBinder.Eval(e.Row.DataItem, "TOTAL"));
}
else if (e.Row.RowType == DataControlRowType.Footer)
{
e.Row.Cells[2].Text = String.Format("{0:N}", totalUnderG);
e.Row.Cells[3].Text = String.Format("{0:N}", totalGrad);
e.Row.Cells[4].Text = String.Format("{0:N}", totalLaw);
e.Row.Cells[5].Text = String.Format("{0:N}", total);
}
}
}
and aspx :
<asp:GridView Width="800px" ID="MyGridView" AutoGenerateColumns="False" OnRowDataBound="MyGridView_RowDataBound"
runat="Server" BorderColor="#555555" HorizontalAlign="Center"
Font-Names="Verdana" Font-Size="12px" AllowSorting="True" ShowFooter="true"
EmptyDataRowStyle-Font-Bold="true" EmptyDataRowStyle-ForeColor="#CC0000">
<EmptyDataTemplate>*** No data available ***</EmptyDataTemplate>
<Columns>
<asp:BoundField FooterText="TTU TOTAL" HeaderText="COLLEGE" DataField="COLLEGE" ItemStyle-HorizontalAlign="Left" HeaderStyle-BackColor="#CC0000" HeaderStyle-ForeColor="#FFFFFF" FooterStyle-HorizontalAlign="Right"
ReadOnly="true" DataFormatString="{0:N0}" />
<asp:BoundField HeaderText="COLLEGE NAME" DataField="COLLEGE DESC" ItemStyle-HorizontalAlign="Left" HeaderStyle-BackColor="#CC0000" HeaderStyle-ForeColor="#FFFFFF" FooterStyle-HorizontalAlign="Right"
ReadOnly="true" DataFormatString="{0:N0}" />
<asp:BoundField HeaderText="UNDERGRAD" DataField="UNDERGRADUATE" ItemStyle-HorizontalAlign="Right" HeaderStyle-ForeColor="#FFFFFF" FooterStyle-HorizontalAlign="Right"
HeaderStyle-BackColor="#CC0000" ReadOnly="true" DataFormatString="{0:N0}"/>
<asp:BoundField HeaderText="GRAD" DataField="GRADUATE" ItemStyle-HorizontalAlign="Right" HeaderStyle-ForeColor="#FFFFFF" FooterStyle-HorizontalAlign="Right"
HeaderStyle-BackColor="#CC0000" ReadOnly="true" DataFormatString="{0:N0}"/>
<asp:BoundField HeaderText="LAW" DataField="LAW" ItemStyle-HorizontalAlign="Right" HeaderStyle-ForeColor="#FFFFFF" FooterStyle-HorizontalAlign="Right"
HeaderStyle-BackColor="#CC0000" ReadOnly="true" DataFormatString="{0:N0}"/>
<asp:BoundField HeaderText="TOTAL" DataField="TOTAL" ItemStyle-HorizontalAlign="Right" FooterStyle-HorizontalAlign="Right" HeaderStyle-ForeColor="#FFFFFF"
HeaderStyle-BackColor="#CC0000" ReadOnly="true" DataFormatString="{0:N0}"/>
</Columns>
</asp:GridView>
<p>
<asp:Button ID="Button1" runat="server" OnClick="Export_Click" Text="Export" />
</p>

Related

ASP.net prevent gridview row click in edit mode

I have some issue with ASP.net Gridview that I hope people here can help me.
Requirements
Gridview whole row to be clickable to open another page
In editing mode, can change table values through edititemtemplate textbox
Problem
Textbox selection causes the entire row click event to fire and prevents user from changing the textbox text. User can edit table value without opening different page.
ASP Page
<asp:GridView ID="remarksGV1" runat="server" AllowPaging="true" DataKeyNames="REM_ID"
OnRowDataBound="remarksGV1_RowDataBound" OnSelectedIndexChanged="remarksGV1_SelectedIndexChanged"
OnRowEditing="remarksGV1_RowEditing"
OnRowCancelingEdit="remarksGV1_RowCancelingEdit"
OnRowUpdating="remarksGV1_RowUpdating"
AutoPostBack="false"
HeaderStyle-CssClass="thead-dark"
CssClass="table table-striped thead-dark table-borderless table-hover border-0 hand"
AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="No.">
<ItemTemplate>
<%# Container.DataItemIndex + 1 %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Title">
<ItemTemplate>
<asp:Label ID="titleLbl" runat="server" Text='<%# Bind("REM_TITLE") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="titleTB" runat="server" />
</EditItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="REM_DESC" HeaderText="Remarks Description" ReadOnly="true" />
<asp:BoundField DataField="CREATE_DATE" DataFormatString="{0:d}" HeaderText="Date Created" ReadOnly="true" />
<asp:BoundField DataField="UPD_DATE" DataFormatString="{0:d}" HeaderText="Last Updated" ReadOnly="true" />
<asp:TemplateField>
<ItemTemplate>
<asp:Button Text="Edit" ID="EditBtn" CssClass="btn-action" runat="server" CommandName="Edit" />
</ItemTemplate>
<EditItemTemplate>
<asp:Button Text="Update" ID="UpdateBtn" CssClass="btn-action" runat="server" CommandName="Update" />
<asp:Button Text="Cancel" ID="CancelBtn" CssClass="btn-action" runat="server" CommandName="Cancel" />
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code behind
private void BindGrid()
{
Debug.WriteLine("BindGrid called");
int proj_code = Int32.Parse(ViewState["proj_cd"].ToString());
ProjectRepository remarksRepository = new ProjectRepository();
var remarks = remarksRepository.GetRemarks(proj_code, proj_task_code, proj_stask1_cd, proj_stask2_cd);
remarksGV1.DataSource = remarks;
remarksGV1.DataBind();
}
protected void Unnamed_Click(object sender, EventArgs e)
{
Launch.PageEvent(this, (LinkButton)sender, ViewState["proj_cd"].ToString());
}
protected void remarksGV1_RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
switch (e.Row.RowType)
{
case DataControlRowType.Header:
//...
break;
case DataControlRowType.DataRow:
e.Row.Attributes.Add("onclick", Page.ClientScript.GetPostBackEventReference(remarksGV1, "Select$" + e.Row.RowIndex.ToString()));
break;
}
}
catch
{
//...throw
}
if (e.Row.RowType == DataControlRowType.DataRow)
{
TextBox titleTB = (e.Row.FindControl("titleTB") as TextBox);
int prj_cd = Int32.Parse(ViewState["proj_cd"].ToString());
ProjectRepository repository = new ProjectRepository();
var remarks = repository.GetRemarks(prj_cd, proj_task_code, proj_stask1_cd, proj_stask2_cd);
Debug.WriteLine("Remarks Count: " + remarks.Count);
TMS_PROJ_REMARK remark = remarks.First(x => x.REM_ID == Convert.ToInt64(DataBinder.Eval(e.Row.DataItem, "REM_ID")));
if (titleTB != null)
{
titleTB.Text = remark.REM_TITLE;
}
}
}
protected void remarksGV1_SelectedIndexChanged(object sender, EventArgs e)
{
int row = remarksGV1.SelectedIndex;
long rem_id = (long)remarksGV1.DataKeys[row]["REM_ID"];
Debug.WriteLine("REM ID: " + rem_id);
Session["edit_remarks"] = true;
Dictionary<string, string> pairs = new Dictionary<string, string>();
pairs["rem_id"] = rem_id.ToString();
pairs["proj_cd"] = ViewState["proj_cd"].ToString();
Launch.ToPage(this, "Project_Remarks_In_2.aspx", pairs);
}
protected void btnAddRemarks_Click(object sender, EventArgs e)
{
Session["new_remarks"] = true;
Dictionary<string, string> pairs = new Dictionary<string, string>();
pairs["proj_cd"] = ViewState["proj_cd"].ToString();
string url = "Project_Remarks_In_1.aspx";
Launch.ToPage(this, url, pairs);
}
private void SetTitle()
{
ProjectRepository repository = new ProjectRepository();
TMS_PROJ_MASTER project = repository.GetProject(Convert.ToInt32(ViewState["proj_cd"]));
this.Title = "Remarks - " + project.PROJ_TITLE;
}
protected void remarksGV1_RowEditing(object sender, GridViewEditEventArgs e)
{
remarksGV1.EditIndex = e.NewEditIndex;
BindGrid();
}
protected void remarksGV1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
// Do stuff
ProjectRepository repository = new ProjectRepository();
GridViewRow row = remarksGV1.Rows[e.RowIndex];
TextBox titleTB = (row.FindControl("titleTB") as TextBox);
long rem_id = Convert.ToInt64(remarksGV1.DataKeys[e.RowIndex].Value);
var db = new THPEntities();
TMS_PROJ_REMARK remark = db.TMS_PROJ_REMARK
.First(x => x.REM_ID == rem_id);
remark.REM_TITLE = titleTB.Text;
remark.UPD_DATE = DateTime.Now;
db.SaveChanges();
// Bind Grid
remarksGV1.EditIndex = -1;
BindGrid();
}
protected void remarksGV1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
remarksGV1.EditIndex = -1;
BindGrid();
}
I suggest in this part of your code, do not add the full line click when you edit the line (I have add one -if- to check for the edit).
switch (e.Row.RowType)
{
case DataControlRowType.Header:
//...
break;
case DataControlRowType.DataRow:
if((e.Row.RowState & DataControlRowState.Edit) != DataControlRowState.Edit)
e.Row.Attributes.Add("onclick", Page.ClientScript.GetPostBackEventReference(remarksGV1, "Select$" + e.Row.RowIndex.ToString()));
break;
}

When i am trying to get excel export, Button_click do nothing ASP.NET C#

When i am trying to get excel export from my mysqldatabase, it doesnt do anything on button_click. I can see that gridview is filling by DataTable but on postback it doesnt download the excel output of my gridview.I cant find out that where is the problem. Thanks for helping guys.
Here is my .aspx gridview code
<asp:GridView ID="GridView1" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White"
RowStyle-BackColor="#A1DCF2" AlternatingRowStyle-BackColor="White" AlternatingRowStyle-ForeColor="#000"
runat="server" AutoGenerateColumns="false" AllowPaging="true" OnPageIndexChanging="OnPageIndexChanging">
<Columns>
<asp:BoundField DataField="isbn" HeaderText="isbn" ItemStyle-Width="150px" />
<asp:BoundField DataField="display_name" HeaderText="bookName" ItemStyle-Width="100px" />
<asp:BoundField DataField="authorName" HeaderText="authorName" ItemStyle-Width="100px" />
</Columns>
Here is my databind and button click
private void BindGrid()
{
DataTable dt = book.getAllbookExcelExport();
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void btnExport_ServerClick(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
using (StringWriter sw = new StringWriter())
{
HtmlTextWriter hw = new HtmlTextWriter(sw);
//To Export all pages
GridView1.AllowPaging = false;
this.BindGrid();
GridView1.HeaderRow.BackColor = Color.White;
foreach (TableCell cell in GridView1.HeaderRow.Cells)
{
cell.BackColor = GridView1.HeaderStyle.BackColor;
}
foreach (GridViewRow row in GridView1.Rows)
{
row.BackColor = Color.White;
foreach (TableCell cell in row.Cells)
{
if (row.RowIndex % 2 == 0)
{
cell.BackColor = GridView1.AlternatingRowStyle.BackColor;
}
else
{
cell.BackColor = GridView1.RowStyle.BackColor;
}
cell.CssClass = "textmode";
}
}
GridView1.RenderControl(hw);
//style to format numbers to string
string style = #"<style> .textmode { } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
}
Here is my page_load
protected void Page_Load(object sender, EventArgs e)
{
Page.Form.Attributes.Add("enctype", "multipart/form-data");
ScriptManager scriptManager = ScriptManager.GetCurrent(this.Page);
scriptManager.RegisterPostBackControl(btnSave);
if (!Page.IsPostBack)
{
this.BindGrid();
}
}

export Gridview to Excel using ClosedXML without warning: the file you are trying to open is in a different format

I am working on a ASP.NET 4.5 Webform and I have a Gridview (that has custom TemplateField and gets data from a sqlDataSource)
I have this event to export the gridview contents to an excel sheet, and it does its jobs well except the created file is giving out an warning when user open it (which I understand because the file that got created is not an actual excel file):
"the file you are trying to open is in a different format than
specified by the file extension"
protected void btnExport_Excel_Click(object sender, EventArgs e)
{
try
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=GV.xls");
Response.Charset = "";
Response.ContentType = "application/ms-excel";
//Response.ContentType = "application/text";
Response.ContentEncoding = System.Text.Encoding.Unicode;
Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());
using (StringWriter sw = new StringWriter())
{
HtmlTextWriter hw = new HtmlTextWriter(sw);
//To Export all pages
GridView4.AllowPaging = false;
GridView4.AllowSorting = false;
GridView4.ShowFooter = false;
GridView4.DataBind();
//this.BindGrid();
GridView4.HeaderRow.BackColor = Color.White;
foreach (TableCell cell in GridView4.HeaderRow.Cells)
{
cell.BackColor = GridView4.HeaderStyle.BackColor;
}
foreach (GridViewRow row in GridView4.Rows)
{
row.BackColor = Color.White;
foreach (TableCell cell in row.Cells)
{
if (row.RowIndex % 2 == 0)
{
cell.BackColor = GridView4.AlternatingRowStyle.BackColor;
}
else
{
cell.BackColor = GridView4.RowStyle.BackColor;
}
cell.CssClass = "textmode";
}
}
GridView4.RenderControl(hw);
//style to format numbers to string
string style = #"<style> .textmode { } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
//Display message
InfoPanel.Visible = true;
InfoPanel.CssClass = "panel panel-success";
lblMessage.CssClass = "text text-sucess bold";
lblMessage.Text = "File has been exported!";
}
catch (Exception ex)
{
//Display message
InfoPanel.Visible = true;
lblMessage.Text = "<b>An error has occurred. Please try again later!</b></br>" + ex.Message;
lblMessage.CssClass = "text text-danger bold";
InfoPanel.CssClass = "panel panel-danger";
panelResult.Visible = false;
}
}
the result in the Excel .xls file is good (no styles except header columns, no footer, just exact as shown on the Gridview):
I am finding another way to avoid this warning, so I see people like to use
ClosedXML, so I replace that event above with this event:
protected void ExportExcel(object sender, EventArgs e)
{
DataTable dt = new DataTable("GridView_Data");
foreach(TableCell cell in GridView4.HeaderRow.Cells)
{
dt.Columns.Add(cell.Text);
}
foreach (GridViewRow row in GridView4.Rows)
{
dt.Rows.Add();
for (int i=0; i<row.Cells.Count; i++)
{
dt.Rows[dt.Rows.Count - 1][i] = row.Cells[i].Text;
}
}
using (XLWorkbook wb = new XLWorkbook())
{
wb.Worksheets.Add(dt);
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment;filename=GV.xlsx");
using (MemoryStream MyMemoryStream = new MemoryStream())
{
wb.SaveAs(MyMemoryStream);
MyMemoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.End();
}
}
}
and the result is bad (only good new is that the exported file is a real 2007+ Excel sheet so no warnings):
How do I get the "good" result above using closedXML?
The main problem in you second part of code (with ClosedXML) , that you are trying to use Text property of GridViewRow for TemplateField field columns. As you can see here, you can get field value via Text property only for BoundField field columns and automatically generated field columns.
To get value from TemplateField you should navigate to inner control which contains value and get value from it.
If you have the following column template:
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="labelName" runat="server" Text ='<%# Eval("ABC")%>' ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
Your code should be:
for (int i=0; i<row.Cells.Count; i++)
{
dt.Rows[dt.Rows.Count - 1][i] = (row.Cells[i].FindControl("labelName") as Label).Text;
}
EDIT
Your code should be as follows:
protected void ExportExcel(object sender, EventArgs e)
{
DataTable dt = new DataTable("GridView_Data");
foreach (DataControlField col in GridView4.Columns)
{
dt.Columns.Add(col.HeaderText);
}
foreach (GridViewRow row in GridView4.Rows)
{
dt.Rows.Add();
for (int i = 0; i < row.Cells.Count; i++)
{
dt.Rows[dt.Rows.Count - 1][i] = (FindControl(row.Cells[i].Controls, "lbl") as Label).Text;
}
}
//your code below is not changed
}
protected Control FindControl(ControlCollection collection, string id)
{
foreach (Control ctrl in collection)
{
if (ctrl.ID == id)
return ctrl;
}
return null;
}
Ensure that all Label controls used in TemplateField have the same ID as "lbl":
<asp:TemplateField HeaderText="ID">
<ItemTemplate>
<asp:Label ID="lbl" runat="server" Text ='<%# Eval("ID")%>' ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="lbl" runat="server" Text ='<%# Eval("Name")%>' ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Amount">
<ItemTemplate>
<asp:Label ID="lbl" runat="server" Text ='<%# Eval("Amount")%>' ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
I tried it's working ,please find the code hope it will help you:
Index.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Index.aspx.cs" Inherits="ExportExcel.Index" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" HeaderStyle-BackColor="#3AC0F2" HeaderStyle- ForeColor="White"
runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Id" HeaderText="Id" ItemStyle-Width="30" />
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:TextBox ID="txtName" runat="server" Text='<%#Eval("Name") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Country">
<ItemTemplate>
<asp:Label ID="lblCountry" Text='<%# Eval("Country") %>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br />
<asp:Button ID="btnExport" Text="Export" runat="server" OnClick="btnExport_Click" />
</div>
</form>
Index.aspx.cs
using ClosedXML.Excel;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace ExportExcel
{
public partial class Index : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
GetData();
}
}
private void GetData()
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Id", typeof(int)), new DataColumn("Name", typeof(string)), new DataColumn("Country", typeof(string)) });
dt.Rows.Add(1, "abc", "UK");
dt.Rows.Add(2, "def", "India");
dt.Rows.Add(3, "ghi", "France");
dt.Rows.Add(4, "jkl", "Russia");
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void btnExport_Click(object sender, EventArgs e)
{
try
{
DataTable dt = new DataTable("GridView_Data");
foreach (TableCell cell in GridView1.HeaderRow.Cells)
{
dt.Columns.Add(cell.Text);
}
foreach (GridViewRow row in GridView1.Rows)
{
TextBox txtNameRow = (TextBox)row.FindControl("txtName");
Label lblCountryRow = (Label)row.FindControl("lblCountry");
DataRow drow = dt.NewRow();
for (int i = 0; i < GridView1.Columns.Count; i++)
{
drow[i] = row.Cells[i].Text;
}
drow["Name"] = txtNameRow.Text;
drow["Country"] = lblCountryRow.Text;
dt.Rows.Add(drow);
}
using (XLWorkbook wb = new XLWorkbook())
{
wb.Worksheets.Add(dt);
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment;filename=GV.xlsx");
using (MemoryStream MyMemoryStream = new MemoryStream())
{
wb.SaveAs(MyMemoryStream);
MyMemoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.End();
}
}
}
catch (Exception ex)
{
throw;
}
}
}
}
I call the Export to Excel on a button click event like the following
protected void btnPrint_Click(object sender, EventArgs e)
{
fileName = string.Format(fileName, DateTime.Now.ToString("MMddyyyy_hhmmss"));
Extensions.ExportToXcel_SomeReport(dt, fileName, this.Page);
}
from there I have a utils class called Extensions where I have the ExportToExcel_SomeReport method defined
public static class Extensions
{
internal static void ExportToXcel_SomeReport(DataTable dt, string fileName, Page page)
{
var recCount = dt.Rows.Count;
RemoveHtmlSpecialChars(dt);
fileName = string.Format(fileName, DateTime.Now.ToString("MMddyyyy_hhmmss"));
var xlsx = new XLWorkbook();
var ws = xlsx.Worksheets.Add("Some Report Name");
ws.Style.Font.Bold = true;
ws.Cell("C5").Value = "YOUR REPORT NAME";
ws.Cell("C5").Style.Font.FontColor = XLColor.Black;
ws.Cell("C5").Style.Font.SetFontSize(16.0);
ws.Cell("E5").Value = DateTime.Now.ToString("MM/dd/yyyy HH:mm");
ws.Range("C5:E5").Style.Font.SetFontSize(16.0);
ws.Cell("A7").Value = string.Format("{0} Records", recCount);
ws.Style.Font.Bold = false;
ws.Cell(9, 1).InsertTable(dt.AsEnumerable());
ws.Row(9).InsertRowsBelow(1);
// ws.Style.Font.FontColor = XLColor.Gray;
ws.Columns("1-9").AdjustToContents();
ws.Tables.Table(0).ShowAutoFilter = true;
ws.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
DynaGenExcelFile(fileName, page, xlsx);
}
/// <summary>
/// Remove all HTML special characters from datatable field if they are present
/// </summary>
/// <param name="dt"></param>
private static void RemoveHtmlSpecialChars(DataTable dt)
{
for (int rows = 0; rows < dt.Rows.Count; rows++)
{
for (int column = 0; column < dt.Columns.Count; column++)
{
dt.Rows[rows][column] = dt.Rows[rows][column].ToString().Replace(" ", string.Empty);
}
}
}
/// <summary>
/// Call this Method to Generate the Excel Files from different Lap Reports depending on which one has been selected
/// </summary>
/// <param name="fileName"></param>
/// <param name="page"></param>
/// <param name="xlsx"></param>
private static void DynaGenExcelFile(string fileName, Page page, XLWorkbook xlsx)
{
page.Response.ClearContent();
page.Response.ClearHeaders();
page.Response.ContentType = "application/vnd.ms-excel";
page.Response.AppendHeader("Content-Disposition", string.Format("attachment;filename={0}.xlsx", fileName));
using (MemoryStream memoryStream = new MemoryStream())
{
xlsx.SaveAs(memoryStream);
memoryStream.WriteTo(page.Response.OutputStream);
}
page.Response.Flush();
page.Response.End();
}
}
Contrary to popular belief, you can set the extension of your file to be .html, and Excel can open it up.
Just set the extension to HTML:
Response.AddHeader("content-disposition", "attachment;filename=GV.html");
And retain Excel as the content type:
Response.ContentType = "application/ms-excel";
EDIT: Oh, right, forgot to mention, this should make that annoying dialog go away.
EDIT 2: Looks like the original question has changed... now it's talking about using ClosedXML... but I'll leave this answer here just in case someone else is using HTML and Excel.

Write GridView to .csv file c# asp.net

I am working on developing a website where customers order directly from our website. I had code working until a few days ago when I changed how the GridView was edited. I had previously set the GridView to AutoGenerate Columns, and have changed that since I needed more functionality for the edit feature. Here is how I create the table (created when user clicks a button to add a quick detail with the GridView):
public void CreateTable()
{
try
{
DataTable table = new DataTable();
if (Session["table"] != null)
table = (DataTable)Session["table"];
else
{
table.Columns.Add("Part Number", typeof(string));
table.Columns.Add("Quantity", typeof(Int32));
table.Columns.Add("Ship-To", typeof(string));
table.Columns.Add("Requested Date", typeof(string));
table.Columns.Add("Shipping Method", typeof(string));
}
DataRow row = table.NewRow();
row["Part Number"] = part;
row["Quantity"] = qty;
row["Ship-To"] = shipto;
row["Requested Date"] = reqdate;
row["Shipping Method"] = shipmthd;
table.Rows.Add(row);
Session["table"] = table;
griditems.DataSource = table.DefaultView;
griditems.DataBind();
}
catch
{
//error message
}
}
This displays the Gridview and allows users to edit/delete the items as they choose. Then I have another button that is displayed when the GridView is created that actually writes the .csv file to the server (my computer for the moment until deployment). Here is the code for that:
protected void orderbtn_Click(object sender, EventArgs e)
{
try
{
//ordernum++;
//custordernum = ordernum.ToString("0000000");
if (userlbl.Visible == false && userlbl2.Visible == false)
{
GlobalList.OnlineOrderNum.Add(custordernum, ordernum);
FileStream fs = new FileStream(#"C:\Web_Order\Orders.Bin", FileMode.Create);
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(fs, GlobalList.OnlineOrderNum);
fs.Close();
fs.Dispose();
///Write CSV File For Order
StringBuilder strBuilder = new StringBuilder();
TextWriter tw = new StreamWriter(#"C:\Web_Order\Order_W" + custordernum.ToString() + ".csv");
foreach (GridViewRow row in griditems.Rows)
{
foreach (TableCell cell in row.Cells)
{
// get cell's text
string cellText = cell.Text;
// add quotes and comma around value and append
strBuilder.Append("\"" + cellText + "\",");
}
strBuilder.Append("\n");
}
// output CSV result
tw.Write(strBuilder.ToString());
tw.Close();
tw.Dispose();
GlobalList.weborder = "W" + custordernum.ToString();
Response.Redirect("~/OrderSubmitted.aspx");
}
else
{
validatelbl.Text = "CANNOT SUBMIT FORM WITH ERRORS. PLEASE CORRECT YOUR ERRORS BEFORE SUBMITTING.";
validatelbl.Visible = true;
userlbl.Text = "Please correct your table with the correct information before submitting your order";
userlbl.Visible = true;
userlbl2.Text = "Are your Part Numbers correct? Are your Quantities in the correct format?";
userlbl2.Visible = true;
}
}
catch
{
//error message
}
}
Here's my edit/delete code for the GridView:
protected void griditems_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
griditems.PageIndex = e.NewPageIndex;
BindData();
}
protected void griditems_RowEditing(object sender, GridViewEditEventArgs e)
{
//Set the edit index.
griditems.EditIndex = e.NewEditIndex;
//Bind data to the GridView control.
BindData();
}
protected void griditems_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
//Reset the edit index.
griditems.EditIndex = -1;
//Bind data to the GridView control.
BindData();
}
protected void griditems_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
string valtext = "An error has occured, please check and make sure your editing is in the correct format and try again.";
orderbtn.Visible = false;
try
{
TextBox editpart = (TextBox)griditems.Rows[e.RowIndex].FindControl("partedit");
TextBox editqty = (TextBox)griditems.Rows[e.RowIndex].FindControl("qtyedit");
TextBox editshipto = (TextBox)griditems.Rows[e.RowIndex].FindControl("shiptoedit");
System.Web.UI.WebControls.Calendar editcal = (System.Web.UI.WebControls.Calendar)griditems.Rows[e.RowIndex].FindControl("reqdatecaledit");
DropDownList editshipmthd = (DropDownList)griditems.Rows[e.RowIndex].FindControl("shipmthdedit");
string newpart = editpart.Text.ToString();
int newqty = Convert.ToInt32(editqty.Text);
string newshipto = editshipto.Text.ToString();
string newreqdate = editcal.SelectedDate.ToShortDateString();
string newshipmthd = editshipmthd.SelectedItem.ToString();
//Reset date if calendar date is not changed so it is not null!
if (newreqdate == "1/1/0001")
newreqdate = reqdate;
DataTable dt = (DataTable)Session["table"];
DataRow dr = dt.Rows[e.RowIndex];
dr["Part Number"] = newpart;
dr["Quantity"] = newqty;
dr["Ship-TO"] = newshipto;
dr["Requested Date"] = newreqdate;
dr["Shipping Method"] = newshipmthd;
dr.AcceptChanges();
Session["table"] = dt;
if (validatelbl.Text == valtext)
validatelbl.Visible = false;
griditems.EditIndex = -1;
BindData();
orderbtn.Visible = true;
}
catch
{
validatelbl.Text = valtext;
validatelbl.Visible = true;
}
}
protected void griditems_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
try
{
//DataTable dt = table;
DataTable dt = (DataTable)Session["table"];
if (dt.Rows.Count > 0)
{
dt.Rows.RemoveAt(e.RowIndex + griditems.PageIndex * 10);
griditems.DataSource = dt;
BindData();
}
}
catch
{
validatelbl.Text = "An error occured while processing your request deleting a record. Please try again.";
validatelbl.Visible = true;
}
}
Here's the aspx code for the gridview:
<asp:GridView ID="griditems" runat="server"
onrowdeleting="griditems_RowDeleting" onrowediting="griditems_RowEditing" onrowupdating="griditems_RowUpdating"
AllowPaging="True"
onpageindexchanging="griditems_PageIndexChanging" Onrowcancelingedit="griditems_RowCancelingEdit"
Caption="Order Details" AutoGenerateDeleteButton="True"
AutoGenerateEditButton="True"
AutoGenerateColumns="False" >
<EditRowStyle BackColor="#FF9900" BorderStyle="Double"/>
<HeaderStyle Font-Bold="True" Font-Italic="False" />
<RowStyle HorizontalAlign="Center"/>
<Columns>
<asp:TemplateField HeaderText="Part Number">
<ItemTemplate>
<asp:Label ID = "partlbl" runat="server" Text='<%#Eval("Part Number") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="partedit" runat="server" Text='<%# Eval("Part Number")%>' ></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Quantity">
<ItemTemplate>
<asp:Label ID = "qtylbl" runat="server" Text='<%#Eval("Quantity") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="qtyedit" runat="server" Text='<%# Eval("Quantity")%>' ></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Ship-To">
<ItemTemplate>
<asp:Label ID = "shiptolbl" runat="server" Text='<%#Eval("Ship-To") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="shiptoedit" runat="server" Text='<%# Eval("Ship-To")%>' ></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Requested Date">
<ItemTemplate>
<asp:Label ID = "reqdatelbl" runat="server" Text='<%#Eval("Requested Date") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Calendar ID="reqdatecaledit" runat="server" BackColor="White" BorderColor="#3366CC" BorderWidth="1px" CellPadding="1"
DayNameFormat="Shortest" Font-Names="Verdana" Font-Size="8pt" ForeColor="#003399" Height="200px" Width="220px"
ondayrender="reqdatecal_DayRender" ShowGridLines="True">
<DayHeaderStyle BackColor="#99CCCC" ForeColor="#336666" Height="1px" />
<DayStyle BackColor="White" />
<NextPrevStyle Font-Size="8pt" ForeColor="#CCCCFF" />
<OtherMonthDayStyle ForeColor="#999999" />
<SelectedDayStyle BackColor="#FF9900" Font-Bold="True" ForeColor="#CCFF99" />
<SelectorStyle BackColor="#99CCCC" ForeColor="#336666" />
<TitleStyle BackColor="#003399" BorderColor="#3366CC" BorderWidth="1px" Font-Bold="True" Font-Size="10pt" ForeColor="#CCCCFF"
Height="25px" />
<TodayDayStyle BackColor="#99CCCC" ForeColor="White" />
<WeekendDayStyle BackColor="#CCCCFF" /></asp:Calendar>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Shipping Method">
<ItemTemplate><asp:Label ID="shipmthdlbl" runat="server" Text='<%#Eval("Shipping Method") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="shipmthdedit" runat="server">
<asp:ListItem>FedEx Ground (1-5 Business Days)</asp:ListItem>
<asp:ListItem>FedEx 3 Business Days</asp:ListItem>
<asp:ListItem>FedEx 2 Business Days</asp:ListItem>
<asp:ListItem>FedEx Overnight</asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
I don't understand why it was working all this time and now all of the sudden it is not working. It creates the file with the new ordernumber as it should, its just the .csv file is empty (no data at all) Any thoughts?
You can correct your path, and replace TextWriter with StreamWriter
var path = Path.Combine("C:\Web_Order\Order_W",custordernum.ToString(),".csv");
StreamWriter tw = new StreamWriter(#path);
Or use directly var.
var tw = new StreamWriter(#path);
Adjust your code with try catch block in order to treat exception if occurs
try
{
}
catch(Exception ex)
{
Console.Write(ex.Message);
throw ex;
}
Not sure why you're using TextWriter here, and you don't need to redirect. Just write to Response.Write().
protected void btnDownload_Click(object sender, EventArgs e)
{
// No error so write as attachment
Response.ContentType = "text/csv";
Response.AddHeader("content-disposition", "attachment;filename=data.csv");
// Write your output here
Response.Write(...);
Response.End();
}

Remove Checkboxes while exporting Gridview to Excel

I have a gridview that needs to be exported to Excel. I have managed to remove the Checkboxes from Rows but don't know how to remove from the Header and also delete the Checkbox Column entirely. Thanks for help.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4" DataKeyNames="Id">
<Columns>
<asp:TemplateField HeaderText="Select" >
<HeaderTemplate>
<input id="chkAll" onclick="checkAll(this);" runat="server" type="checkbox" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Event" HeaderText="Event" SortExpression="Event" />
<asp:BoundField DataField="Event_Description" HeaderText="Event_Description" SortExpression="Event_Description" />
<asp:BoundField DataField="Start_Date" HeaderText="Start_Date" SortExpression="Start_Date" />
</Columns>
</asp:GridView>
Here's the backend C# code to export to excel.
protected void download_Click(object sender, EventArgs e)
{
PrepareGridViewForExport(GridView1);
Response.ClearContent();
Response.AddHeader("content-disposition", "attachment; filename=GridViewToExcel.xls");
Response.ContentType = "application/excel";
StringWriter sWriter = new StringWriter();
HtmlTextWriter hTextWriter = new HtmlTextWriter(sWriter);
GridView1.RenderControl(hTextWriter);
Response.Write(sWriter.ToString());
Response.End();
}
public override void VerifyRenderingInServerForm(Control control)
{
}
private void PrepareGridViewForExport(Control gv)
{
Literal l = new Literal();
string name = String.Empty;
for (int i = 0; i < gv.Controls.Count; i++)
{
if (gv.Controls[i].GetType() == typeof(CheckBox))
{
gv.Controls.Remove(gv.Controls[i]);
gv.Controls.AddAt(i, l);
}
if (gv.Controls[i].HasControls())
{
PrepareGridViewForExport(gv.Controls[i]);
}
}
}
Try out this export function , which hides not needed column i.e column 0 of the row...
protected void btnExportExcel_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView1.DataBind();
GridView1.HeaderRow.Cells[0].Visible = false;
for (int i = 0; i < GridView1.Rows.Count;i++ )
{
GridViewRow row = GridView1.Rows[i];
row.Cells[0].Visible = false;
row.Cells[0].FindControl("chkCol0").Visible = false;
}
GridView1.RenderControl(hw);
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.End();
}
or
On your export, drop the column. Something something like:
GridView1.Columns[0].visible = false;
GridView1.DataBind();
GridView1.RenderControl(htmlWrite);
Response.Write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />");
Instead of hiding the control we can remove them before exporting into Excel.This can be done by looping through the cell and find the controls present in the cell. Then identify the control type and remove them from that cell.
Following is the code:
foreach (GridViewRow row in GridView1.Rows)
{
row.BackColor = Color.White;
foreach (TableCell cell in row.Cells)
{
cell.CssClass = "textmode";
for (int i = 0; i < cell.Controls.Count; i++)
{
Control ctr = cell.Controls[i];
if (ctr is TextBox)
cell.Controls.Remove(ctr);
else if (ctr is DropDownList)
cell.Controls.Remove(ctr);
else if (ctr is Label)
{
if (ctr.ClientID.Contains("lblrow"))
cell.Controls.Remove(ctr);
}
}
}
}
In the above code I am looping through the each row and cells. Then removing all the TextBox, DropdownList and Label with the ID lblrow which are present there.

Categories