exporting gridview to word - asp.net

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

Related

Error while converting gridview with paging into excel

I am using the following code to convert gridview to ms-excel format. The problem is this if i use following code one 1st page is converted into ms-ecxel
protected void Button1_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
string file1 = TextBox1.Text + ".xls";
string attachment = string.Format("attachment;filename={0}", file1);
this.EnableViewState = false;
Response.AddHeader("content-disposition", attachment);
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/ms-excel";
using (StringWriter sw = new StringWriter())
{
HtmlTextWriter htw = new HtmlTextWriter(sw);
GridView1.RenderControl(htw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
}
and if add these two lines to my code i"ll get blank ms-excel sheet
GridView1.AllowPaging = false;
this.Emp_Wrklog();
please do the needful changes in my code so that i can cnvert my gridview having paging into excel. Thanks in advance.
You should definitely use EPPlus library or something like that for manipulating excel files.
http://epplus.codeplex.com/

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 from GridView to Excel save popup not working

I want to export data from GridView into an excel file on ASP.NET website. I added a GridView only for this purpose
<body>
<form id="mainForm" runat="server">
<asp:GridView ID="exportGrid" runat="server">
</asp:GridView>
</form>
....
</body>
In codebehind I have this:
public override void VerifyRenderingInServerForm(Control control) { }
var result = GetDataIQueryable(); //A method that returns an IQueryable
exportGrid.DataSource = result;
exportGrid.DataBind();
Response.Clear();
Response.ClearContent();
Response.AddHeader("content-disposition", "attachment; filename=" + "ExcelFile.xls");
Response.ContentType = "application/excel";
var sw = new System.IO.StringWriter();
var htw = new HtmlTextWriter(sw);
exportGrid.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
The problem is that the popup that allows me to save the excel file on my computer is not appearing. What should I change in my code ?
Use this code on your button click event
protected void btnExport_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=FormReport.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;
BindGridView();
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();
GridView1.Dispose();
}
}
#endregion
public override void VerifyRenderingInServerForm(Control control)
{
/* Verifies that the control is rendered */
}
and on .aspx page use
<%# Page Title="" Language="C#" EnableEventValidation="false"%>
I know this is a bit too late, but i am posting this just for information. I found the answer in the comments but i would still like to submit a answer with code , because i myself found it difficult to find the code so the answer is for if your grid is inside update panel. You need to add a post back trigger to the button.
private void RegisterPostBackControl()
{
ScriptManager.GetCurrent(this).RegisterPostBackControl(yourButton);
}
public override void VerifyRenderingInServerForm(Control control)
{
/* Verifies that the control is rendered */
}
Your Buttons Click Event :
protected void yourButton_Click(object sender, EventArgs e)
{
ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", "full", true);
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=FormReport.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
using (StringWriter sw = new StringWriter())
{
HtmlTextWriter hw = new HtmlTextWriter(sw);
//To Export all pages
yourGrid.AllowPaging = false;
var emps = FunctionThatGetsGridValues();
yourGrid.DataSource = emps;
yourGrid.DataBind();
yourGrid.HeaderRow.BackColor = Color.White;
foreach (TableCell cell in yourGrid.HeaderRow.Cells)
{
cell.BackColor = yourGrid.HeaderStyle.BackColor;
}
foreach (GridViewRow row in yourGrid.Rows)
{
row.BackColor = Color.White;
foreach (TableCell cell in row.Cells)
{
if (row.RowIndex % 2 == 0)
{
cell.BackColor = yourGrid.AlternatingRowStyle.BackColor;
}
else
{
cell.BackColor = yourGrid.RowStyle.BackColor;
}
cell.CssClass = "textmode";
}
}
yourGrid.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();
yourGrid.Dispose();
}
}
And On Page Load Dont forget to add :
protected void Page_Load(object sender, EventArgs e)
{
this.RegisterPostBackControl();
}

How to export dynamically created table to excel?

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 */
}

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

Resources