how to export a grid view in to excel? - c#

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();
}

Related

How to hide to columns when exporting GridView to Excel?

How can I hide two columns when I export my GridView to excel.
So at the moment this is how it looks like when I export:
-------------------------------------------------------------------------
| Display Name | Email Address | License | | |
-------------------------------------------------------------------------
| User 1 | email#email.com | 1 | edit | delete |
-------------------------------------------------------------------------
| User 2 | email1#email.com | 1 | edit | delete |
-------------------------------------------------------------------------
As you can see the last two columns are links within my GridView to edit and delete the row
Those two columns I don't want to export to excel as it looks unprofessional.
Is there a way to remove those two columns (or hide) when exporting to excel?
This is my code I am using:
protected void ExportToExcel(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=UserExport.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();
}
}
This might work. It should basically copy the gridview to a new gridveiw and then remove the last two columns ready for the rest of your code.
protected void ExportToPDF(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=UserExport.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
using (StringWriter sw = new StringWriter())
{
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView gv = GridView1;
gv.Columns.RemoveAt(4);
gv.Columns.RemoveAt(3);
//To Export all pages
gv.AllowPaging = false;
this.BindGrid();
gv.HeaderRow.BackColor = Color.White;
foreach (TableCell cell in gv.HeaderRow.Cells)
{
cell.BackColor = gv.HeaderStyle.BackColor;
}
foreach (GridViewRow row in gv.Rows)
{
row.BackColor = Color.White;
foreach (TableCell cell in row.Cells)
{
if (row.RowIndex % 2 == 0)
{
cell.BackColor = gv.AlternatingRowStyle.BackColor;
}
else
{
cell.BackColor = gv.RowStyle.BackColor;
}
cell.CssClass = "textmode";
}
}
gv.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();
}
}
Well a not so elegant solution can always be that you use just a normal for loop instead of the foreach. This would mean that you can just skip the last two columns.
protected void ExportToExcel(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=UserExport.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
TableCell cell;
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;
for(int i = 0; i < row.Cells.Count()-2; i++)
{
cell = row.Cells[i];
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();
}
}

How to Export multiple header Gridview Data to Excel

I have a gridview which has multiple headers added during run time as shown in snap below:
I want to export the data from this gridview to excel for which I have the following code:
protected void Button1_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);
gdView.HeaderRow.BackColor = Color.White;
foreach (TableCell hcell in gdView.HeaderRow.Cells)
{
hcell.BackColor = Color.White;
}
foreach (GridViewRow row in gdView.Rows)
{
{
row.BackColor = Color.White;
foreach (TableCell cell in row.Cells)
{
cell.CssClass = "textmode";
}
}
}
gdView.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();
}
}
public override void VerifyRenderingInServerForm(System.Web.UI.Control control)
{
// controller
}
The excel output I am getting is as follows:
As you can see the color of the header rows is continuing beyond the table area. Also the top header rows are collapsed in the excel output.
Request you all to kindly suggest how this can be resolved.
Thanks.
I could finally solve the issue by modifying the code as below:
protected void Button1_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);
for (int x = 0; x <= 3; x++)
{
GridViewRow rows = (GridViewRow)gdView.HeaderRow.Parent.Controls[x];
rows.BackColor = Color.White;
rows.Height = 15;
for (int i = 0; i <= rows.Cells.Count - 1; i++)
{
rows.Cells[i].BackColor = Color.Maroon;
}
}
foreach (GridViewRow row in gdView.Rows)
{
row.BackColor = Color.White;
foreach (TableCell cell in row.Cells)
{
cell.VerticalAlign = VerticalAlign.Middle;
cell.CssClass = "textmode";
}
}
gdView.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();
}
}
public override void VerifyRenderingInServerForm(System.Web.UI.Control control)
{
// controller
}

Export only Gridview Data to Excel format in Asp.net C#

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

Export Large Data to Excel

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);

Export DataGridView with padding to excel

save data gird view to excel in asp dot net. data is save when i am using padding in grid view than full data not show in excel sheet how to show full data of grid view in excel sheet when using padding in grid view
protected void btnexcel_Click1(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition",
"attachment;filename=ActualsAndBudgets.xls");
Response.Charset = "";
Response.ContentType = "application/ms-excel";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gvdetails.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}
public override void VerifyRenderingInServerForm(Control control)
{
}
You can export to excel and apply styles and formatting see sample code below
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);
GridView.AllowPaging = false;
// Re-Bind data to GridView
using (MSEntities1 CompObj = new MSEntities1())
{
// code for bind grid view
GridView.DataBind();
}
// Change the Header Row back to white color
GridViewC.Style.Add(" font-size", "10px");
GridView.HeaderRow.Style.Add("background-color", "#FFFFFF");
//Apply style to Individual Cells
GridView.HeaderRow.Cells[0].Style.Add("background-color", "green");
GridView.HeaderRow.Cells[1].Style.Add("background-color", "green");
GridView.HeaderRow.Cells[2].Style.Add("background-color", "green");
GridView.HeaderRow.Cells[3].Style.Add("background-color", "green");
GridView.HeaderRow.Cells[4].Style.Add("background-color", "green");
GridView.HeaderRow.Cells[5].Style.Add("background-color", "green");
GridView.HeaderRow.Cells[6].Style.Add("background-color", "green");
GridView.HeaderRow.Cells[7].Style.Add("background-color", "green");
int k = GridView.Rows.Count;
for (int i = 1; i < GridView.Rows.Count; i++)
{
GridViewRow row = GridView.Rows[i];
//Change Color back to white
row.BackColor = System.Drawing.Color.White;
//Apply text style to each Row
row.Attributes.Add("class", "textmode");
//Apply style to Individual Cells of Alternating Row
if (i % 2 != 0)
{
row.Cells[0].Style.Add("background-color", "#C2D69B");
row.Cells[1].Style.Add("background-color", "#C2D69B");
row.Cells[2].Style.Add("background-color", "#C2D69B");
row.Cells[3].Style.Add("background-color", "#C2D69B");
row.Cells[4].Style.Add("background-color", "#C2D69B");
row.Cells[5].Style.Add("background-color", "#C2D69B");
row.Cells[6].Style.Add("background-color", "#C2D69B");
row.Cells[7].Style.Add("background-color", "#C2D69B");
}
}
GridView.RenderControl(hw);
// style to format numbers to string.
string style = #"<style> .textmode { mso-number-format:\#; } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
Go through following code:
using System;
using System.Data;
using System.IO;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Whatever
{
///
/// This class provides a method to write a dataset to the HttpResponse as
/// an excel file.
///
public class ExcelExport
{
public static void ExportDataSetToExcel(DataSet ds, string filename)
{
HttpResponse response = HttpContext.Current.Response;
// first let's clean up the response.object
response.Clear();
response.Charset = "";
// set the response mime type for excel
response.ContentType = "application/vnd.ms-excel";
response.AddHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");
// create a string writer
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
// instantiate a datagrid
DataGrid dg = new DataGrid();
dg.DataSource = ds.Tables[0];
dg.DataBind();
dg.RenderControl(htw);
response.Write(sw.ToString());
response.End();
}
}
}
}
}
NOTE: Above code belongs to this link.
You can follow discussion over that link and get more details.
Hope its helpful.

Categories