ASP.Net Grid Export to Excel - c#

I am using following code to export my GridView to Excel:
string attachment = "attachment; filename=Contacts.xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gvReports.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
This code is copied from this site. I have followed all the instructions but after executing nothing happened. No exception (Except Thread.Abort which is, I think, because of Response.End()).
I have also used Response.Flush() BUT nothing is happening no exception or file etc.
Thanks.
EDIT Now Code Is like following:
My GridView is in Control. The control is on asp.net page and that page has following method.
public override void VerifyRenderingInServerForm(Control control)
{
}
Click event of button in ascx control:
protected void btnExportToExcel_Click(object sender, EventArgs e)
{
ExportToExcel();
}
private void ExportToExcel()
{
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);
gvReports.AllowPaging = false;
gvReports.DataBind();
gvReports.RenderControl(hw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
gvReports has no link, checkbox etc. 5 bound columns and 1 button.
Nothing is happening.

itextsharp dlls ,you will get the best method to do that
Click here

I'm using MVC3 for my solution, but the code I'm using to push data out to an excel file is:
var grid = new GridView
{
DataSource = from lineItem in rows
select new
{
lineItem.ProjectName,
lineItem.Sat,
lineItem.Sun,
lineItem.Mon,
lineItem.Tue,
lineItem.Wed,
lineItem.Thu,
lineItem.Fri
}
};
var fileName = string.Format("{0}:{1}", userName, timesheetDate);
grid.DataBind();
Response.ClearContent();
Response.AddHeader("content-disposition", "attachment; filename=" + fileName + ".xls");
Response.ContentType = "application/msexcel";
var sw = new StringWriter();
var htw = new HtmlTextWriter(sw);
grid.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
The immediate differences that I see are:
I take my data and create a new GridView
Response.ClearContent() instead of a Response.Clear()
Response.Write instead of Response.Output.Write
Everything else looks the same, and we both are using a click event to call a void function. So I'm guessing that if you make those few changes, your code should start working for you.
It's been a while since I implemented this solution and I couldn't find the sites that I got this off of so I can't show you my original sources. Sorry about that.

UserControl code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
public partial class WebUserControl : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
this.gridView.DataSource = this.SqlDataSource1;
this.gridView.DataBind();
}
private void excel_Export()
{
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);
this.gridView.AllowPaging=false;
this.gridView.DataBind();
this.gridView.RenderControl(hw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
protected void Button1_Click(object sender, EventArgs e)
{
excel_Export();
}
}
User Control Hosting page:
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<uc1:WebUserControl ID="WebUserControl1" runat="server" />
</asp:Content>
You really dont need following event in code behind of User control hosting page, because excel export is being done via user control which contains grid view and button.
public override void VerifyRenderingInServerForm(Control control)
{
/* Verifies that the control is rendered */
}
Hopefully this will you help to solve the issue.

Related

Date issue while export to excel in asp.net

protected void ExportToExcel(object sender, EventArgs e)
{
Response.ClearContent();
Response.AddHeader("content-disposition", "attachment;filename=Detail.xls");
Response.ContentType = "application/excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htm = new HtmlTextWriter(sw);
Repeater repAllUsers = this.rptrRegistrationReport;
repAllUsers.DataSource = objAdmin.Getregdetails(start, enddate, usrtype);
repAllUsers.DataBind();
repAllUsers.RenderControl(htm);
Response.Write("<Table border='1'" + "cellSpacing='0' cellPadding='0' " +"style='font-size:12.0pt; '>");
Response.Write(sw.ToString());
Response.End();
}
All data are export proper but only date column showing #####.How to show date in excel file.

data transfer gird view to excel sheet

data transfer grid view to excel in asp dot net code is run but blank sheet generate of excel but data is not loaded in excel sheeet how to solve this type of broblem
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.AllowPaging = false;
gvdetails.DataBind();
gvdetails.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}
public override void VerifyRenderingInServerForm(Control control)
{
}
Check for data in the gridview, your data is not getting binded. So the excel is empty. Debug and check for data inside the gridview. It should work.
Try with this one
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);
GridView1.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
may be problem in data binding in export excel .
check that data properly bin to a gridview or not.
Use this code for export grid view in excel sheet and note that you must add iTextSharp dll in you project.
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.AllowPaging = false;
// Re-Bind data to GridView
using (CompMSEntities1 CompObj = new CompMSEntities1())
{
Start = Convert.ToDateTime(txtStart.Text);
End = Convert.ToDateTime(txtEnd.Text);
GridViewSummaryReportCategory.DataSource = CompObj.SP_Category_Summary(Start, End);
SP_Category_Summary_Result obj1 = new SP_Category_Summary_Result();
GridView1.DataBind();
GridView1.Visible = true;
ExportTable.Visible = true;
}
//Change the Header Row back to white color
GridView1.HeaderRow.Style.Add("background-color", "#FFFFFF");
GridView1.Style.Add(" font-size", "10px");
//Apply style to Individual Cells
GridView1.HeaderRow.Cells[0].Style.Add("background-color", "green");
GGridView1.HeaderRow.Cells[1].Style.Add("background-color", "green");
GridView1.HeaderRow.Cells[2].Style.Add("background-color", "green");
GridView1.HeaderRow.Cells[3].Style.Add("background-color", "green");
GridView1.HeaderRow.Cells[4].Style.Add("background-color", "green");
for (int i = 1; i < GridView1.Rows.Count; i++)
{
GridViewRow row = GridView1.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");
}
}
GridView1.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();
}

Exporting GridView to XLS --- Paging Issue

I have a GridView and I intend to export it into .xls file. Paging is enabled in this gridview. The codes I am currently using can only export the first page of the gridview.
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition","attachment;filename=DataTable.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
//As you notice, below I tried to disable the paging yet it's unsuccessful
//FYI I am able to really prevent first column, header row, and footer row to
//be exported through this
gvGridView.Columns[0].Visible = false;
gvGridView.HeaderRow.Visible = false;
gvGridView.FooterRow.Visible = false;
gvGridView.AllowPaging = false;
for (int i = 0; i < gvGridView.Rows.Count; i++)
{
gvGridView.Rows[i].Attributes.Add("class", "textmode");
}
gvGridView.RenderControl(hw);
string style = #"<style> .textmode { mso-number-format:\#; } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
I noticed this question was previously asked yet there was no correct answer.
Any help is appreciated.
Thank's
You should rebind your GridView after you specify gvGridView.AllowPaging = false;, then export. Otherwise .RenderControl(hw); will only be rendering the currently selected GridView page.
Just make a GridView.DataBind() after change the AllowPaging property.

export GridView to excel #2

I am binding a GridView to a sqldatasource and then on _rowcreated event doing some validations and when the row does not meet requirements I am hiding it using e.Row.Visible = false;
This works fine and only displays the correct rows in the gridview. Now I have a button to export to excel and that works great with the exception of exporting also the hidden rows. I do not want the hidden rows exported.
Is there a way that i can tell the gridview to not add that row instead of hiding it?
Is there a simple method to delete all hidden rows before i run the export?
Can i not add the hidden rows during the export? As you can see in the code below I tried to do this one, but it does not recognize whether the row is visible or not.
Export Code:
public static void Export(string fileName, GridView gv)
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader(
"content-disposition", string.Format("attachment; filename={0}", fileName));
HttpContext.Current.Response.ContentType = "application/ms-excel";
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
// Create a form to contain the grid
Table table = new Table();
gv.GridLines = GridLines.Both;
table.GridLines = gv.GridLines;
//table.BackColor = Color.Yellow;
// add the header row to the table
if (gv.HeaderRow != null)
{
GridViewExportUtil.PrepareControlForExport(gv.HeaderRow);
table.Rows.Add(gv.HeaderRow);
//color the header
table.Rows[0].BackColor = gv.HeaderStyle.BackColor;
table.Rows[0].ForeColor = gv.HeaderStyle.ForeColor;
}
// add each of the data rows to the table
foreach (GridViewRow row in gv.Rows)
{
if (row.Visible == true)
{
GridViewExportUtil.PrepareControlForExport(row);
table.Rows.Add(row);
}
}
// color the rows
bool altColor = false;
for (int i = 1; i < table.Rows.Count; i++)
{
if (!altColor)
{
table.Rows[i].BackColor = gv.RowStyle.BackColor;
altColor = true;
}
else
{
table.Rows[i].BackColor = gv.AlternatingRowStyle.BackColor;
altColor = false;
}
}
// render the table into the htmlwriter
table.RenderControl(htw);
// render the htmlwriter into the response
HttpContext.Current.Response.Write(sw.ToString());
HttpContext.Current.Response.End();
}
}
}
http://mattberseth.com/blog/2007/04/export_gridview_to_excel_1.html
I have never used GridViewExportUtil, but why not edit his code?
private static void PrepareControlForExport(Control control)
{
for (int i = 0; i < control.Controls.Count; i++)
{
Control current = control.Controls[i];
//-----------------------------
// * my addition
if (!current.Visible) continue;
//-----------------------------
if (current is LinkButton)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as LinkButton).Text));
}
else if (current is ImageButton)
{
//...
Here is the simple implementation to Export GridView to Excel:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
public partial class ExportGridView : System.Web.UI.Page
{
protected void Button1_Click(object sender, EventArgs e)
{
Response.Clear();
Response.AddHeader("content-disposition", "attachment;
filename=FileName.xls");
Response.Charset = "";
// If you want the option to open the Excel file without saving than
// comment out the line below
// Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite =
new HtmlTextWriter(stringWrite);
GridView1.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
}
}
Reference blog
In the first place why you have hidden rows from your gridview? Only get data that you wanted. And use this method to export;
void ExportToExcel(GridView grdData, string filename)
{
grdData.BorderStyle = BorderStyle.Solid;
grdData.BorderWidth = 1;
grdData.BackColor = Color.WhiteSmoke;
grdData.GridLines = GridLines.Both;
grdData.Font.Name = "Verdana";
grdData.Font.Size = FontUnit.XXSmall;
grdData.HeaderStyle.BackColor = Color.DimGray;
grdData.HeaderStyle.ForeColor = Color.White;
grdData.RowStyle.HorizontalAlign = HorizontalAlign.Left;
grdData.RowStyle.VerticalAlign = VerticalAlign.Top;
HttpResponse response = HttpContext.Current.Response;
response.Clear();
response.Charset = "";
response.ContentType = "application/vnd.ms-excel";
response.AddHeader("Content-Disposition", "attachment;filename=\"" + filename+ "\"");
using (var sw = new StringWriter())
{
using (var htw = new HtmlTextWriter(sw))
{
grdData.RenderControl(htw);
response.Write(sw.ToString());
response.End();
}
}
}

Column Values Customisation- Export Excel in ASP.NET

I have to export gridview in to the excel sheet 2003. With my code I can Export the data into eXcel Sheet directly. But If there is a null value for the column, Then how do I replace with empty string in Excel sheet. There is a date column which is null, is there any event handler that occurs between export button click and the loading the data into excel. If there is one I can compare the values in the database and can replace the null value with empty String. in the evnt handler.
Please point me in right direction.
Thank you
On click of the export button, you can iterate through your grid rows and replace whatever you need. For example, the code below will replace : with .:
protected void btnExport_Click(object sender, EventArgs e)
{
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
string attachment = "attachment; filename=SummaryReport" + DateTime.Now.ToString() + ".xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/ms-excel";
foreach (GridViewRow grdRow in grdProjectTasks.Rows)
{
Label lblActualDuration = (Label)grdRow.FindControl("lblActualDuration");
lblActualDuration.Text = lblActualDuration.Text.Replace(":", ".");
}
grdProjectTasks.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}

Categories

Resources