Export data from Gridview to Excel in asp.net - c#

I am Having Error while Exporting data from Gridview to Excel in asp.net
Firebug shows that error is
"Error: Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed. Common causes for this error are when the response is modified by calls to Response.Write(), response filters, HttpModules, or server trace is enabled.
Details: Error parsing near '
and my code is
EditUser _editUser = new EditUser();
string s = Request.QueryString["UserName"];
DataTable _dsLeaveDetails1 = new DataTable();
_dsLeaveDetails1 = _editUser.GetUserWiseECO(s.ToLower(), "Earned Comp Off");
if (_dsLeaveDetails1.Rows.Count > 0)
{
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "MonthlyLeaveReport.xls"));
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
sample.AllowPaging = false;
sample.DataSource = _dsLeaveDetails1;
sample.DataBind();
//Change the Header Row back to white color
sample.HeaderRow.Style.Add("background-color", "#FFFFFF");
//Applying stlye to gridview header cells
for (int i = 0; i < sample.HeaderRow.Cells.Count; i++)
{
sample.HeaderRow.Cells[i].Style.Add("background-color", "#507CD1");
}
int j = 1;
//This loop is used to apply stlye to cells based on particular row
foreach (GridViewRow gvrow in sample.Rows)
{
gvrow.BackColor = Color.White;
if (j <= sample.Rows.Count)
{
if (j % 2 != 0)
{
for (int k = 0; k < gvrow.Cells.Count; k++)
{
gvrow.Cells[k].Style.Add("background-color", "#EFF3FB");
}
}
}
j++;
}
sample.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}
else
{
ScriptManager.RegisterStartupScript(this, GetType(), "displayalertmessage", "alert('No records Found!!!');", true);
}

This is the complete code I'm using.
First override this method:
public override void VerifyRenderingInServerForm(Control control)
{
}
And use this method to export to Excel:
private void ExportToExcel()
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=name.xls");
Response.Charset = "utf-8";
Response.ContentType = "application/vnd.ms-excel";
using (StringWriter sw = new StringWriter())
{
HtmlTextWriter hw = new HtmlTextWriter(sw);
//To Export all pages
gridview.AllowPaging = false;
gridview.HeaderRow.BackColor = Color.White;
foreach (TableCell cell in gridview.HeaderRow.Cells)
{
cell.BackColor = Color.FromName("#4091A4");
cell.ForeColor = Color.White;
foreach (Control control in cell.Controls)
{
if ((control.GetType().Name == "DataControlLinkButton") ||
(control.GetType().Name == "DataControlLinkButton"))
{
cell.Controls.Add(new Literal { Text = (control as LinkButton).Text });
cell.Controls.Remove(control);
}
}
}
foreach (GridViewRow row in gridview.Rows)
{
row.BackColor = Color.White;
foreach (TableCell cell in row.Cells)
{
List<Control> controls = new List<Control>();
foreach (Control control in cell.Controls)
{
controls.Add(control);
}
cell.CssClass = "textmode";
foreach (Control control in controls)
{
switch (control.GetType().Name)
{
case "HyperLink":
cell.Controls.Add(new Literal { Text = (control as HyperLink).Text });
break;
case "TextBox":
cell.Controls.Add(new Literal { Text = (control as TextBox).Text });
break;
case "DataControlLinkButton":
case "LinkButton":
cell.Controls.Add(new Literal { Text = (control as LinkButton).Text });
break;
case "CheckBox":
cell.Controls.Add(new Literal { Text = (control as CheckBox).Text });
break;
case "RadioButton":
cell.Controls.Add(new Literal { Text = (control as RadioButton).Text });
break;
}
cell.Controls.Remove(control);
}
if (row.RowIndex % 2 == 0)
{
cell.BackColor = gridview.AlternatingRowStyle.BackColor;
}
else
{
cell.BackColor = gridview.RowStyle.BackColor;
}
cell.HorizontalAlign = HorizontalAlign.Center;
}
}
gridview.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();
}
}

Related

button to export tables to excel in asp.net

I have few pages of tables, and I have created a button to export the table to excel. my problem is that it only export the current page of table that in at and not all the pages? can anyone help me out?
protected void ExportToExcel(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;
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";
}
}

How to manually add Excel columns headers for a generated spreadsheet

I have developed an excel sheet using c# gridview. How do I add a header row and set column names via code. This is my current code...
protected void ExportToExcel1(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;
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();
}
}

Export multiple gridviews to multiple excel tabs (sheets)

I have 6 gridviews in my website that I need to export to excel, but each one in one different sheet.
This link Export GridView to multiple Excel sheet uses something quite similar, but he is using datasets and I am not. I am new to C#, so I couldnt change it to fit my solution.
My code exports all gridviews to the same sheet. I created a loop to run throught my gridviews, now I need to put a code to generate each one to each excel sheet.
protected void btExcel_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=FARPOP_Mensal_" + txDt.Text + ".xls");
Response.ContentEncoding = System.Text.Encoding.GetEncoding("Windows-1252");
Response.Charset = "ISO-8859-1";
Response.ContentType = "application/vnd.ms-excel";
using (StringWriter sw = new StringWriter())
{
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView[] gvExcel = new GridView[] { gvAnual, gvPorUF, gvPorFarmacia, gvPorMunicipio, gvPorPV, gvPorCNPJ };
for (int i = 0; i < gvExcel.Length; i++)
{
GridView gv = gvExcel[i];
//
// Need to redirect to each sheet here?
//
gvExcel[i].HeaderRow.BackColor = Color.White;
gvExcel[i].UseAccessibleHeader = false;
gvExcel[i].AllowPaging = false;
for (int x = 0; x < gvExcel[i].Columns.Count; x++)
{
gvExcel[i].Columns[x].Visible = true;
}
gvExcel[i].DataBind();
foreach (TableCell cell in gvExcel[i].HeaderRow.Cells)
{
cell.BackColor = Color.CadetBlue;
cell.Enabled = false;
}
foreach (GridViewRow row in gvExcel[i].Rows)
{
row.BackColor = Color.White;
foreach (TableCell cell in row.Cells)
{
cell.Controls.Clear();
if (row.RowIndex % 2 == 0)
{
cell.BackColor = Color.White;
}
else
{
cell.BackColor = Color.LightBlue;
}
cell.CssClass = "textmode";
}
}
gvExcel[i].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();
}
}
I followed maniak1982 comments and found a good solution.
So, if you need multiple gridviews to multiples worksheets, using .NET, you will need to download ClosedXML and also DocumentFormat.OpenXml.dll.
After referencing the dll, use the following code:
protected void btExcel_Click(object sender, EventArgs e)
{
XLWorkbook wb = new XLWorkbook();
GridView[] gvExcel = new GridView[] { GridView1, GridView2, GridView3, GridView4, GridView5, GridView6};
string[] name = new string[] { "Name1", "Name2", "Name3", "Name4", "Name5", "Name6" };
for (int i = 0; i < gvExcel.Length; i++)
{
if (gvExcel[i].Visible)
{
gvExcel[i].AllowPaging = false;
gvExcel[i].DataBind();
DataTable dt = new DataTable(name[i].ToString());
for (int z = 0; z < gvExcel[i].Columns.Count; z++)
{
dt.Columns.Add(gvExcel[i].Columns[z].HeaderText);
}
foreach (GridViewRow row in gvExcel[i].Rows)
{
dt.Rows.Add();
for (int c = 0; c < row.Cells.Count; c++)
{
dt.Rows[dt.Rows.Count - 1][c] = row.Cells[c].Text;
}
}
wb.Worksheets.Add(dt);
gvExcel[i].AllowPaging = true;
}
}
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment;filename=Workbook_Name.xlsx");
using (MemoryStream MyMemoryStream = new MemoryStream())
{
wb.SaveAs(MyMemoryStream);
MyMemoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.End();
}
}
It took me days of searching... But it's working perfectly.
Be happy

Export gridview in excel

I have two gridviews on a page. When I click on Button3 it exports gridview data to excel perfectly.
but when I click on Button5 it exports data of gridview to excel and in excel file contains only:
<style> .textmode { } </style><div>
here is my c# code:
protected void Button3_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=ExportFile.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
using (StringWriter sw = new StringWriter())
{
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView1.AllowPaging = false;
GridView1.Columns[0].Visible = false;
GridView1.Columns[1].Visible = false;
//GridView1.HeaderRow.Style.Add("background-color", "#FFFFFF");
this.GridView1.DataBind();
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();
}
}
protected void Button5_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=ExportFile.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
using (StringWriter sw = new StringWriter())
{
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView2.AllowPaging = false;
GridView2.Columns[0].Visible = false;
GridView2.Columns[1].Visible = false;
//GridView1.HeaderRow.Style.Add("background-color", "#FFFFFF");
this.GridView2.DataBind();
GridView2.HeaderRow.BackColor = Color.White;
foreach (TableCell cell in GridView2.HeaderRow.Cells)
{
cell.BackColor = GridView2.HeaderStyle.BackColor;
}
foreach (GridViewRow row in GridView2.Rows)
{
row.BackColor = Color.White;
foreach (TableCell cell in row.Cells)
{
if (row.RowIndex % 2 == 0)
{
cell.BackColor = GridView2.AlternatingRowStyle.BackColor;
}
else
{
cell.BackColor = GridView2.RowStyle.BackColor;
}
cell.CssClass = "textmode";
}
}
GridView2.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();
}
}

Download Selected Row of Gridview to excel

I need to download selected rows of an asp.net gridview to an excel sheet.
What I am doing is trying the check all at once or just a few selected and then after pressing the download button below, all the selected rows get downloaded as excel. Every thing works fine here when I press download button, but rather all the rows get downloaded ignoring the selection.
Following is my code
public void ExportGridToExcel(GridView grdGridView, string fileName)
{
Response.Clear();
Response.AddHeader("content-disposition", string.Format("attachment;filename={0}.xls", fileName));
Response.Charset = "";
Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);
Response.ContentType = "application/vnd.xls";
StringWriter stringWriter = new StringWriter();
HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);
// I Tried using following (but with no success)
//-----Trial Starts----------------
//foreach (GridViewRow gvr in gvProgramList.Rows)
// {
// CheckBox cbox = (CheckBox)gvr.FindControl("cboxSelect");
// if(cbox.Checked)
// gvr.Visible = true;
// else
// gvr.Visible = false;
// }
//--------Trial ends---------------
grdGridView.DataBind();
ClearControls(grdGridView);
// Throws exception: Control 'ComputerGrid' of type 'GridView'
// must be placed inside a form tag with runat=server.
// ComputerGrid.RenderControl(htmlWrite);
// Alternate to ComputerGrid.RenderControl above
System.Web.UI.HtmlControls.HtmlForm form = new System.Web.UI.HtmlControls.HtmlForm();
Controls.Add(form);
form.Controls.Add(grdGridView);
form.RenderControl(htmlWriter);
Response.Write(stringWriter.ToString());
Response.End();
foreach (GridViewRow gvr in gvProgramList.Rows)
{
CheckBox cbox = (CheckBox)gvr.FindControl("cboxSelect");
gvr.Visible = true;
}
grdGridView.DataBind();
}
private void ClearControls(Control control)
{
for (int i = control.Controls.Count - 1; i >= 0; i--)
{
ClearControls(control.Controls[i]);
}
if (!(control is TableCell))
{
if (control.GetType().GetProperty("SelectedItem") != null)
{
LiteralControl literal = new LiteralControl();
control.Parent.Controls.Add(literal);
try
{
literal.Text =
(string)control.GetType().GetProperty("SelectedItem").
GetValue(control, null);
}
catch
{ }
control.Parent.Controls.Remove(control);
}
else if (control.GetType().GetProperty("Text") != null)
{
LiteralControl literal = new LiteralControl();
control.Parent.Controls.Add(literal);
literal.Text =
(string)control.GetType().GetProperty("Text").
GetValue(control, null);
control.Parent.Controls.Remove(control);
}
}
return;
}
protected void btnDownload_Click(object sender, EventArgs e)
{
if (gvProgramList.Rows.Count > 0)
{
ExportGridToExcel(gvProgramList, "ProgramList");
}
}
I can suggest you a logic to do this:
1.Create a dynamic datatable with selected rows of your gridview.
its just looping through gridview rows and fetching and appending selected rows to new datatable.
2.Then write code for converting this new datatable to excel sheets(lots of results for google "Convert datatable to excel")
Try like the below code,hope it helps you..
On the download button click event,call this fn
private void ExportToExcell()
{
DataTable dt = new DataTable();
dt.Columns.Add("Plan ID");
dt.Columns.Add("Plan Name");
dt.Columns.Add("Balance");
foreach (GridViewRow row in gdvBal.Rows)
{
CheckBox chkCalls = (CheckBox)row.FindControl("chkCalls");
if (chkCalls.Checked == true)
{
int i = row.RowIndex;
Label lblPlanId = (Label)gdvBal.Rows[i].FindControl("lblPlanId");
Label lblPlanName = (Label)gdvBal.Rows[i].FindControl("lblPlanName");
Label lblBalance = (Label)gdvBal.Rows[i].FindControl("lblBalance");
DataRow dr = dt.NewRow();
dr["Plan ID"] = Convert.ToString(lblPlanId.Text);
dr["Plan Name"] = Convert.ToString(lblPlanName.Text);
dr["Balance"] = Convert.ToString(lblBalance.Text);
dt.Rows.Add(dr);
}
}
GridView gdvExportxls = new GridView();
gdvExportxls.DataSource = dt;
gdvExportxls.DataBind();
Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/ms-excel";
Response.AddHeader("content-disposition", string.Format("attachment;filename=BillingForfBalances.xls", "selectedrows"));
Response.Charset = "";
StringWriter stringwriter = new StringWriter();
HtmlTextWriter htmlwriter = new HtmlTextWriter(stringwriter);
gdvExportxls.RenderControl(htmlwriter);
Response.Write(stringwriter.ToString().Replace("<div>", " ").Replace("</div>", " "));
Response.End();
}

Categories

Resources