I cannot figure out how to export multiple GridViews to excel. This code only exports 1 GridView and I have 10 of them. GridViews should be separated with an empty row. Ideally, I would like to place those GridViews on the same Excel Sheet. Thanks for looking into this.
protected void ExportExcel(object sender, EventArgs e)
{
DataTable dt = new DataTable("GridView_Data");
foreach(TableCell cell in GridView1.HeaderRow.Cells)
{
dt.Columns.Add(cell.Text);
}
foreach (GridViewRow row in GridView1.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=GridView.xlsx");
using (MemoryStream MyMemoryStream = new MemoryStream())
{
wb.SaveAs(MyMemoryStream);
MyMemoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.End();
}
}
}
Any help is appreciated.
Thanks!
Related
I'm trying to export the contents of the gridview to excelsheet and the last row of the gridview is always missing in the excel sheet.
I think it might be due to the header row but could not figure out how to overcome this. Below is the code for exporting to excel sheet
private void btnExportToExcel_OnClick(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.RenderControl(hw); //here gridview is not rendering last row
//style to format numbers to string
string style = #"<style> .textmode { } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
}
This is working fine for me. Here is my code behind with simple data.My aspx page has just a grid and an export button
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("Id");
DataRow dr = dt.NewRow();
dr["Id"] = 1;
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["Id"] = 2;
dt.Rows.Add(dr);
//To Export all pages
grdTest.AllowPaging = false;
grdTest.AllowSorting = false;
grdTest.DataSource = dt;
grdTest.DataBind();
}
public override void VerifyRenderingInServerForm(Control control)
{
/* Verifies that the control is rendered */
}
protected void btnExport_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";
using (StringWriter sw = new StringWriter())
{
HtmlTextWriter hw = new HtmlTextWriter(sw);
grdTest.RenderControl(hw); //here gridview is not rendering last row
//style to format numbers to string
string style = #"<style> .textmode { } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
}
}
I could not found solution online anywhere but I found the reason why this was happening, it was due to one additonal GridviewRow being added to the gridview on rowDatabound, and that addition of single row was skipping the very last row.
To fix this, before gridview databinding, I added one empty footer row to workaround the issue:
DataRow dr= dt.NewRow();
dt.Rows.Add(dr);
GridView1.DataSource = dt;
GridView1.DataBind();
In my page I have two textbox controls, where I am gating the date from the Calendar Extender & in the export to excel Button I am going to export the Gridview data to excel sheet.
When I am gating the excel sheet its show the the textbox & button also from which i am export the excel Sheet.
I have written the export code in the Export Button.
Like:-
protected void Export_to_Excel_Click(object sender, EventArgs e)
{
try
{
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "Customers.xls"));
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
Grd_MidData.AllowPaging = false;
bindgriddata();
//Change the Header Row back to white color
Grd_MidData.HeaderRow.Style.Add("background-color", "#FFFFFF");
//Applying stlye to gridview header cells
for (int i = 0; i < Grd_MidData.HeaderRow.Cells.Count; i++)
{
Grd_MidData.HeaderRow.Cells[i].Style.Add("background-color", "#df5015");
}
Grd_MidData.RenderControl(htw);
Response.Write(sw.ToString());
Response.Flush();
}
catch (Exception ee)
{
}
}
When I am gating the excel sheet it shows the gridview data along with the two text box & the button from where I am doing the filtering.
So any one suggest me, How to show only the gridview data but not show the Textbox & button on the excel sheet.
You have to bind the data to your excel code,
using below code
bindgriddata();
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "Customers.xls"));
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter ht = new HtmlTextWriter(sw);
Grd_MidData.RenderControl(ht);
Response.Write(sw.ToString());
Response.End();
it is working for me.
Here the gridview data is showing along with the From date: To Date: textbox & the button also. So how can i remove these field from the sheet.
you can use close xml to generate excel it will give more functionlity to create excel and formatting.
protected void Export_to_Excel_Click(object sender, EventArgs e)
{
bindgriddata();
Grd_MidData.DataSource = objDS; // Dataset
Grd_MidData.DataBind();
using (XLWorkbook wb = new XLWorkbook())
{
try
{
//creating worksheet
var ws = wb.Worksheets.Add("Report");
//adding columms header
int columnscount = objDS.Tables[0].Columns.Count;
char a = 'A';
for (int j = 1; j <= columnscount; j++)
{
string str = a + "1";
ws.Cell(str).Value = objDS.Tables[0].Columns[j - 1].ColumnName.ToString();
ws.Cell(str).Style.Border.OutsideBorder = XLBorderStyleValues.Thin;
a++;
}
ws.Columns().AdjustToContents();
//formatting columns header
var rngheaders = ws.Range("A1:J1");
rngheaders.FirstRow().Style
.Font.SetBold()
.Font.SetFontSize(12)
.Font.SetFontColor(XLColor.Black)
.Fill.SetBackgroundColor(XLColor.DeepSkyBlue)
.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Center)
.Border.OutsideBorder = XLBorderStyleValues.Thin;
////adding data to excel
int k = 2;
foreach (DataRow row in objDS.Tables[0].Rows)
{
char b = 'A';
string str = b + "" + k;
for (int i = 0; i < objDS.Tables[0].Columns.Count; i++)
{
ws.Cell(str).Value = row[i].ToString();
ws.Cell(str).Style.Border.OutsideBorder = XLBorderStyleValues.Thin;
ws.Cell(str).Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Left);
b++;
str = b + "" + k;
}
k++;
}
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment;filename=Customer.xlsx");
}
catch { }
using (MemoryStream MyMemoryStream = new MemoryStream())
{
wb.SaveAs(MyMemoryStream);
MyMemoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.End();
}
}
}
I had the same issue when exporting a GridView. I added a try/catch and exported the message to Excel and then realized that it was generating an error. I solved it thanks to the following answer: GridView must be placed inside a form tag with runat="server" even after the GridView is within a form tag
In my gridview i have 30000 records,while i export to excel, it export upto near 12000 records only,bellow my code to export to excel.
GridView1.AllowPaging = false;
DataTable dt = (DataTable)Session["tabledata"];
GridView1.DataSource = dt;
GridView1.DataBind();
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "Customers.xls"));
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
//Change the Header Row back to white color
GridView1.HeaderRow.Style.Add("background-color", "Red");
//Applying stlye to gridview header cells
for (int i = 0; i < GridView1.HeaderRow.Cells.Count; i++)
{
GridView1.HeaderRow.Cells[i].Style.Add("background-color", "Red");
}
GridView1.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
Here how can i export all(30k) gridview records to excel?
Here is a sample code to save your grid data to an excel file
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;
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();
}
}
I would suggest that you take a look at OpenXmlWriter class for exporting large amount of data to excel (that should prevent cache problems).
To export data to Excel, you can use the ClosedXML.Report library (https://github.com/ClosedXML/ClosedXML.Report). Believe me, this is a wonderful library and easy for her to use. The library does not need Excel Interop. ClosedXML.Report generates an Excel file based on a template that you can create in Excel using any formatting. For example:
var template = new XLTemplate(#".\Templates\report.xlsx");
using (var db = new DbDemos())
{
var cust = db.customers.LoadWith(c => c.Orders).First();
template.AddVariable(cust);
template.Generate();
}
template.SaveAs(outputFile);
I need to export nested Gridview to Excel with the following code that I get from search, but when I click the Export button it raised an error:
An exception of type 'System.ArgumentOutOfRangeException' occurred in
mscorlib.dll but was not handled in user code
This is the code:
protected void ExportExcel(object sender, EventArgs e)
{
DataTable dt = new DataTable("GridView_Data");
GridView grvPayrollDetails = (GridView)grvPayroll.Rows[1].FindControl("grvPayrollDetails");
foreach (TableCell cell in grvPayroll.HeaderRow.Cells)
{
dt.Columns.Add(cell.Text);
}
foreach (TableCell cell in grvPayrollDetails.HeaderRow.Cells)
{
dt.Columns.Add(cell.Text);
}
dt.Columns.RemoveAt(0);
foreach (GridViewRow row in grvPayroll.Rows)
{
GridView grvPayrollDetailscell = (row.FindControl("grvPayrollDetails") as GridView);
for (int j = 0; j < grvPayrollDetailscell.Rows.Count; j++)
{
dt.Rows.Add(row.Cells[1].Text, row.Cells[2].Text, grvPayrollDetailscell.Rows[j].Cells[0].Text, grvPayrollDetailscell.Rows[j].Cells[1].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=grvPayrollDetails.xlsx");
using (MemoryStream MyMemoryStream = new MemoryStream())
{
wb.SaveAs(MyMemoryStream);
MyMemoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.End();
}
}
}
grvPayroll is the Master Gridview and Gridview grvPayrollDetails is the nested child Gridview. Please help!
I followed this guide: Export Nested GridView (GridView inside GridView) to Excel in ASP.Net
And this is the Nested Gridview :
Nested Gridview
Change your following line GridView grvPayrollDetails = (GridView)grvPayroll.Rows[1].FindControl("grvPayrollDetails"); with below code
GridView grvPayrollDetails = null;
foreach (GridViewRow row in grvPayroll.Rows)
{
if (row.HasControls())
{
foreach (Control ctrl in row.Controls)
{
if (ctrl.ID == "grvPayrollDetails" && grvPayrollDetails != null)
{
grvPayrollDetails = (GridView)ctrl;
break;
}
}
if (grvPayrollDetails != null)
{
break;
}
}
}
you should modify your for loop to run for count - 1, and use if condition to check row.Cells should be >= 3
for (int j = 0; j < grvPayrollDetailscell.Rows.Count - 1; j++)
{
if(row.Cells.Count >= 3)
{
dt.Rows.Add(row.Cells[1].Text, row.Cells[2].Text, grvPayrollDetailscell.Rows[j].Cells[0].Text, grvPayrollDetailscell.Rows[j].Cells[1].Text);
Also makesure your dt.Columns have value before removing column at 0 index
if(dt.Columns.Count > 0)
{
dt.Columns.RemoveAt(0);
}
Try this:
public override void VerifyRenderingInServerForm(Control control)
{
/* Confirms that an HtmlForm control is rendered for the specified ASP.NET
server control at run time. */
}
protected void ExportExcel(object sender, EventArgs e)
{
grvPayroll.AllowPaging = false;
var grvPayrollDetails = new GridView();
for (var i = 0; i < grvPayroll.Rows.Count; i++)
{
grvPayrollDetails = (GridView)grvPayroll.Rows[i].FindControl("grvPayrollDetails");
grvPayrollDetails.AllowPaging = false;
BindGrid(SortField);
}
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=PayrollExport.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
using (StringWriter sw = new StringWriter())
{
HtmlTextWriter hw = new HtmlTextWriter(sw);
grvPayrollDetails.AllowPaging = false;
this.BindGrid(SortField);
grvPayrollDetails.Font.Name = "Times New Roman";
grvPayrollDetails.BackColor = Color.Transparent;
grvPayrollDetails.GridLines = GridLines.Both;
grvPayrollDetails.RenderControl(hw);
Response.Write(Regex.Replace(sw.ToString(), "(<a[^>]*>)|(</a>)", " ", RegexOptions.IgnoreCase));
Response.Flush();
Response.End();
}
}
hi i am developing an application where i am using a grid to dispaly data and adding a dynamic datatable as the header of the gridview and iam using the following code to export the grid view into excel but i am unable get the datatable which was added dynamically to the grid into the excel. the code i am using is:
Response.AddHeader("content-disposition", "attachment;filename=Report.xls");
Response.Charset = String.Empty;
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter sw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView1.DataBind();
GridView1.RenderControl(hw);
Response.Write(sw.ToString());
Response.End();
is thee any other method to follow.
Thanks in advance!
I don't see where you are adding the dynamic datatable as the header?? This should come after the databind and before the GridView1.RenderControl(hw);
try this one in the button click event
protected void btnExcel_Click(object sender, ImageClickEventArgs e)
{
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", string.Format("attachment; filename= {0}", "Customers.xls"));
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gvdetails.AllowPaging = false;
gvdetails.DataBind();
//Change the Header Row back to white color
gvdetails.HeaderRow.Style.Add("background-color", "#FFFFFF");
//Applying stlye to gridview header cells
for (int i = 0; i < gvdetails.HeaderRow.Cells.Count; i++)
{
gvdetails.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 gvdetails.Rows)
{
gvrow.BackColor = Color.White;
if (j <= gvdetails.Rows.Count)
{
if (j % 2 != 0)
{
for (int k = 0; k < gvrow.Cells.Count; k++)
{
gvrow.Cells[k].Style.Add("background-color", "#EFF3FB");
}
}
}
j++;
}
gvdetails.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}
this will export gridview in formatted output file
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename=gridSample.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
using (StringWriter sw = new StringWriter())
{
HtmlTextWriter hw = new HtmlTextWriter(sw);
//to export all pages
gridSample.AllowPaging = false;
gridSample.DataSource = progress.getSample();
gridSample.DataBind();
//bind again
gridSample.HeaderRow.BackColor = Color.White;
foreach (TableCell cell in gridSample.HeaderRow.Cells)
{
cell.BackColor = gridSample.HeaderStyle.BackColor;
}
foreach (GridViewRow row in gridSample.Rows)
{
row.BackColor = Color.White;
foreach (TableCell cell in row.Cells)
{
if (row.RowIndex % 2 == 0)
{
cell.BackColor = gridSample.AlternatingRowStyle.BackColor;
}
else
{
cell.BackColor = gridSample.RowStyle.BackColor;
}
cell.CssClass = "textmode";
}
}
gridSample.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();
}