How to export dynamically created table to excel? - asp.net

In an aspx page:
<asp:table id = "table1" runat ="server"></table>
I have created a table using Javascript from the cs file like this:
StringBuilder sb = new StringBuilder()
sb.Append('<script>') ;
sb.Append(document.write('<table><tr><td>hghj</td></tr></table>'))
Table cell ;
Table row;
cell.Control.Add(new LiteralControl(sb.ToString())) ;
row.Control.Add(cell);
table1.Control.Add(row);
Now I want to export that table to excel, so I used the following code. It opened the excel file. But no data is seen.
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", "attachment; filename=ExcelFile.xls");
Response.ContentEncoding = Encoding.UTF8;
StringWriter tw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(tw);
table1.RenderControl(hw);
Response.Write(tw.ToString());
Response.End();

I had a somewhat similar issue and the following solution worked for me. Hopefully it helps OP and others. In my case, the table data was dynamically being populated at run-time but when I tried to export the data to excel, I was getting a blank excel file. I solved this issue by putting my table generation code outside if (!IsPostBack){}. This is what my code structure looks like after that change:
protected void Page_Load(object sender, EventArgs e)
{
FunctionToPopulateTableDataAtRuntime();
if (!IsPostBack)
{
// other parts of the code
}
}
private void FunctionToPopulateTableDataAtRuntime()
{
// code to dynamically populate table data at run-time
// this code is somewhat similar to that of OP
// but it does not make use of JavaScript whatsoever
}
private void ExportTableToExcel()
{
// the code for this function is somewhat similar to what OP has
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", "attachment; filename=test.xls;");
Response.ContentEncoding = Encoding.UTF8;
StringWriter stringWrite = new StringWriter();
HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
myTable.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
}
protected void btnExportToExcel_Click(object sender, EventArgs e)
{
ExportTableToExcel();
}
This is what the code-front (aspx) looks like:
<asp:Table
ID="myTable"
runat="server">
</asp:Table>
<asp:Button
ID="btnExportToExcel"
runat="server"
Text=" Export to Excel "
OnClick="btnExportToExcel_Click"/>

public override void VerifyRenderingInServerForm(Control control)
{
/* Verifies that the control is rendered */
}

Related

Export data from a Gridview to Excel and save it in a folder

I am trying to export data from a Gridview to Excel and save that Excel file in a folder on the server. I have done the Excel generation part. But I am not able to save that in a folder.
Please find my code below.
Code
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "order.xls"));
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gridX.AllowPaging = false;
bindX();
gridX.HeaderRow.Style.Add("background-color", "#FFFFFF");
for (int i = 0; i < gridX.HeaderRow.Cells.Count; i++)
{
gridX.HeaderRow.Cells[i].Style.Add("background-color", "#df5015");
}
gridX.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
Please help me to solve the issue.
Hope this will help you. First fill the gridview control then use the RenderControl() method to render grid in excel to a specific path.
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 Button1_Click(object sender, EventArgs e)
{
using (StreamWriter sw = new StreamWriter("c:\\test.xls"))
{
using (HtmlTextWriter hw = new HtmlTextWriter(sw))
{
GridView1.RenderControl(hw);
}
}
}

Export Gridview Data to Excel in ASP.NET Linq data bind

I am using bellow code for export gridview data to excel but problem is that whole page export to excel. I want only gridview data not whole page export. How can solve this problem?
HtmlForm form = new HtmlForm();
Response.Clear();
Response.Buffer = true;
string filename = "GridViewExport_" + DateTime.Now.ToString() + ".xls";
Response.AddHeader("content-disposition", "attachment;filename=" + filename);
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
gdvInBox.AllowPaging = false;
gdvInBox.DataBind();
form.Controls.Add(gdvInBox);
this.Controls.Add(form);
form.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();
Thanks in Advance.
It's pretty easy to set up the excel export that will export only the gridview. This has been tested and will only export the gridview that appears on your given web page.
For your C# code use the following:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class vxcel_export : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button2_Click(object sender, EventArgs e)
{
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=file-name.xls");
Response.ContentType = "application/vnd.xlsx";
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();
}
public override void VerifyRenderingInServerForm(Control control)
{
}
}
In your aspx code use the following:
Make sure you add EnableEventValidation="false" to the <%#Page %> code at the top of the page.
Place the following code where you want to put the button to export your gridview to Excel:
<asp:Button ID="Button2" runat="server" OnClick="Button2_Click" Text="Whatever you want your button to say" />
You can modify the Height and Width to whatever size you want in the button.
That's it. One thing to keep in mind is that when you export the file it's not a true excel file until you save it as a workbook/Excel File.
I had to also apply the following code to my page to get this to work.
public override void VerifyRenderingInServerForm(Control control)
{
/* Confirms that an HtmlForm control is rendered for the specified ASP.NET
server control at run time. */
}
I found the solution here --> GridView must be placed inside a form tag with runat="server" even after the GridView is within a form tag

How to export GridView to excelsheet?

I have a gridview in my page. What I want is when user clicks on the button "Export", it should open a box to download a file and save as a excel sheet. I have pagging enabled in my grid but when I export data, all rows must be sent in the excel sheet irrespective of pagging. I can not export my data source(datatable) because it contains few other columns which are hidden but I am using it just for my purpose and dont what to show it to the users.
How can I do so....??? I am not getting any Idea...
As James Johnson said..I did like that. This is the code given by him
protected void btnExport_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/vnd.ms-excel";
Response.Charset = "";
System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
GridView1.RenderControl(oHtmlTextWriter);//Error is thrown from here.
Response.Write(oStringWriter.ToString());
Response.End();
}
But doing this throws following error at from at specified potion in code
Control 'ctl00_ContentPlaceHolder1_ViewAdvances1_grdAdvance' of type 'GridView' must be placed inside a form tag with runat=server.
I have placed gridview in usercontrol, the usercontrol is placed in .aspx page and that page uses master page which already have form tag.
You can try something like this:
protected void btnExport_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/vnd.ms-excel";
Response.Charset = "";
System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
GridView1.RenderControl(oHtmlTextWriter);
Response.Write(oStringWriter.ToString());
Response.End();
}
It's a lot of discussions regarding this:
export gridview rows to excel sheet
Export GridView to Excel
Export gridview into excel in Windowsformsapplication (maybe some useful info you will find here)
Add the following code to your code behind:
Public Overrides Sub VerifyRenderingInServerForm(ByVal control As Control)
'dont delete - needed for excel export
End Sub
I got the solution for export to excel in master page.
put this code after page load code
public override void VerifyRenderingInServerForm(Control control)<br/>
{<br/>
/* Verifies that the control is rendered */<br/>
//base.VerifyRenderingInServerForm(control);
}
then
protected void btnExportExcel_Click(object sender, EventArgs e)<br/>
{<br/>
try<br/>
{<br/>
BindReportdata(ddlReport.SelectedIndex);<br/>
Response.Clear();<br/>
Response.Buffer = true;<br/>
Response.AddHeader("content-disposition",<br/>
"attachment;filename=report.xls");<br/>
Response.ContentType = "application/ms-excel";<br/>
StringWriter sw = new StringWriter();<br/>
HtmlTextWriter hw = new HtmlTextWriter(sw);<br/>
for (int i = 0; i < gv_ReportData.Rows.Count; i++)<br/>
{
GridViewRow row = gv_ReportData.Rows[i];<br/>
}
gv_ReportData.GridLines = GridLines.Both;<br/>
gv_ReportData.RenderControl(hw);<br/>
Response.Write(sw.ToString());<br/>
Response.Flush();<br/>
Response.End();<br/>
}<br/>
catch (Exception ex)<br/>
{<br/>
throw ex;<br/>
}<br/>
}<br/>
and in aspx page use updatepanel and trigger for button

exporting gridview to word

protected void Button2_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition",
"attachment;filename=GridViewExport.doc");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-word ";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView1.AllowPaging = false;
GridView1.RenderControl(hw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
public override void VerifyRenderingInServerForm(Control control)
{
/* Verifies that the control is rendered */
}
this is my code in the .cs file what am trying to do is export a gridview to word file
but when i run the code it gives an error
RegisterForEventValidation can only be called during Render();
pls help
Copying the answer from comment:
got the answer guys EnableEventValidation ="false" just have to add this in the page directive

Why does my Excel export have a blank row at the top?

In ASP.NET, I am exporting some data to Excel by simply binding a DataSet to a GridView and then setting the ContentType to Excel.
My ASPX page is very simple and looks like this:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="ExamExportReport.aspx.cs" Inherits="Cabi.CamCentral.Web.Pages.Utility.ExamExportReport" %>
<html>
<body>
<form id="form1" runat="server">
<asp:GridView
ID="gridExam"
AutoGenerateColumns="true"
runat="server">
</asp:GridView>
</form>
</body>
</html>
In the Page_Load method of the code behind, I am doing this:
protected void Page_Load(object sender, EventArgs e)
{
BindGrid();
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("content-disposition", "attachment; filename=ExamExport.xls");
}
Generally, everything works fine, and the Excel file pops up with the right data. The problem is that the Excel file always ends up with a blank first row right above the column headers. I just can't figure out what is causing this. Maybe it's something about the form tag? Maybe I need to add some styling or something to strip out padding or margins? I've tried a bunch of things but I just can't get rid of that dang first blank row. Has anyone else run into this? Any solutions?
#azamsharp - I found the solution elsewhere while you were replying. :-) It turns out that removing the form tag entirely from the ASPX page is the trick, and the only way to do this is to override the VerifyRenderingInServerForm method as you are doing.
If you update your solution to include the fact that you need to remove the form tag from the page, I will accept your answer. Thanks.
Here is my code that works fine:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindData();
}
}
private void BindData()
{
string connectionString = "Server=localhost;Database=Northwind;Trusted_Connection=true";
SqlConnection myConnection = new SqlConnection(connectionString);
SqlDataAdapter ad = new SqlDataAdapter("select * from products", myConnection);
DataSet ds = new DataSet();
ad.Fill(ds);
gvProducts.DataSource = ds;
gvProducts.DataBind();
}
protected void ExportGridView(object sender, EventArgs e)
{
Response.ClearContent();
Response.AddHeader("content-disposition", "attachment; filename=MyExcelFile.xls");
Response.ContentType = "application/excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gvProducts.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}
public override void VerifyRenderingInServerForm(Control control)
{
}
An easier solution is to override the Render (HtmlTextWriter writer) method and make it empty:
protected override void Render(HtmlTextWriter writer){}
http://c-sharpe.blogspot.com/2009/05/get-rid-of-blank-row-when-exporting-to.html

Resources