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";
}
}
Related
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();
}
}
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();
}
}
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
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();
}
}
I have the code below that generates an excel file when clicked. the code runs fine the formatting of colors is fine. The grid view has data with leading zeros that are not showing in excel along with long numbers "106638660952840428" which show up as 1.06639E+17 with a value of 106638660952840000 so it loses its last four digits as well. I have tried several ways to export all with the same results. I am doing it this way to have the chance at formatting the cells individually.So the question is does anyone know how to dynamically change the format so these problems do not occur? Another thing to add is that the grid-view in a web browser does display the data correctly.
protected void LinkButton6_Click(object sender, EventArgs e)
{
Iframe1.Attributes.Add("src", "blank.aspx");
if (CheckBox5.Checked || CheckBox6.Checked)
{
dt = (DataTable)Cache["dtable"];
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=BemisInventory.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.DataSource = dt;
//GridView1.PageIndex = 0;
GridView1.DataBind();
GridView1.HeaderRow.BackColor = Color.White;
foreach (TableCell cell in GridView1.HeaderRow.Cells)
{
cell.BackColor = Color.White;//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 = Color.White;
}
else
{
cell.BackColor = Color.White; //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();
}
}
}
Fixed by adding: string style = #" .textmode { mso-number-format:\#; } "; comes up with warnings but all data is there.