Error while converting gridview with paging into excel - asp.net

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/

Related

Gridview not getting last row in the Excel file

I wrote a code to fetch the gridview to the Excel. Everything is working fine except a row in the gridview. When i export gridview to excel, then last row doesnot includes in the excel file. When i scanned my whole code, then i found a code which is creating a problem. Here is the code :
protected void OnDataBound(object sender, EventArgs e)
{
GridViewRow row = new GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Normal);
TableHeaderCell cell = new TableHeaderCell();
cell.Text = "A";
cell.ColumnSpan = 9;
row.Controls.Add(cell);
gv.HeaderRow.Parent.Controls.AddAt(0, row);
}
This code is used to add new header to the gridview of merged cells. After removing this code, everything works fine. But i need that code.
Export to excel code :
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=Rept" + DateTime.Now.ToString("yyyy_MM_ddThh_mm_ss_") + ".xls");
Response.Charset = "";
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
System.Web.UI.HtmlControls.HtmlForm form = new System.Web.UI.HtmlControls.HtmlForm();
Controls.Add(form);
form.Controls.Add(gvpanel);
form.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
How to solve this issue ?
I haven't find the solution anywhere, which makes me to provide this solution.
When you create a header row & also you need to export to excel, below code solves of missing the last row.
Create your dynamic header row using RowCreated Event.
protected void Grid_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
GridViewRow HeaderRow = new GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Insert);
TableCell HeaderCell1 = new TableCell();
HeaderCell1.Text = "Solved your Issue";
HeaderCell1.ColumnSpan = 10;
HeaderRow.Cells.Add(HeaderCell1);
Grid.Controls[0].Controls.Add(HeaderRow);
}
}
and now you can call your ExportToExcel method:
private void ExportToExcel(GridView gv, string exportfilename)
{
string filename = exportfilename + ".xls";
System.IO.StringWriter tw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
gv.RenderControl(hw);
//Write the HTML back to the browser.
Response.ContentType = "application/vnd.ms-excel";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + "");
this.EnableViewState = false;
Response.Write(tw.ToString());
Response.Flush();
Response.End();
}
You can use an excel spreadsheet as a data source to your GridView and connect to it like any other database:
How To Query and Display Excel Data by Using ASP.NET, ADO.NET, and Visual Basic .NET

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 to Excel not working in IIS

I am generating excel file and it working fine in local host but not working in IIS.I have a model pop up from where i open pop up window using window.open method where following code is written to generate excel file.
public void GenerateExcelFile(DataTable dt)
{
Response.Clear();
Response.Buffer = true;
string filename = "abc.xls";
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("content-disposition", "attachment; filename=" + filename);
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView gv = new GridView();
gv.AutoGenerateColumns = true;
gv.DataSource = dt;
gv.DataBind();
gv.RenderControl(hw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
Please help me to resolve issue.
Recently we where trying to do this, we ended up using this lovely little library: EPPlus
It made the whole process of making our sheets very easy, clean and efficient. Hopefully it will provide a solution to your problem.

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

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

Resources