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
Related
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 */
}
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
I need to convert either an ASP.NET Datagrid or GridView to excel with a page-break that can be part of the target excel.
The first part to convert the grid control to excel is not that complex and fairly easy to do, but my problem is how to insert a page break to the excel file during the conversion process.
Thanks for the help.
Here is the complete code 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 Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
GridView1.DataSource = BindData();
GridView1.DataBind();
}
}
private string ConnectionString
{
get { return #"Server=localhost;Database=Northwind;
Trusted_Connection=true"; }
}
private DataSet BindData()
{
// make the query
string query = "SELECT * FROM Categories";
SqlConnection myConnection = new SqlConnection(ConnectionString);
SqlDataAdapter ad = new SqlDataAdapter(query, myConnection);
DataSet ds = new DataSet();
ad.Fill(ds, "Categories");
return ds;
}
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();
}
public override void VerifyRenderingInServerForm(Control control)
{
// Confirms that an HtmlForm control is rendered for the
specified ASP.NET server control at run time.
}
}
I am working in asp.net and in that i am using grid view and now i want to convert grid view data which is dynamic to the html table so i can send an email. if any one know it please tell me.
Thank You
You can use
using System.IO;
using System.Text;
using System.Net.Mail;
private string GridViewToHtml(GridView gv)
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
HtmlTextWriter hw = new HtmlTextWriter(sw);
gv.RenderControl(hw);
return sb.ToString();
}
protected void SendMailButton_Click(object sender, EventArgs e)
{
MailMessage mail = new MailMessage();
mail.Body = GridViewToHtml(GridView1);
mail.IsBodyHtml = true;
// The same logic as you use for sending mail
}
public override void VerifyRenderingInServerForm(Control control)
{
}
The Kettic GridView control can easily export the data in GridView to HTML and create an html format file to viewing in a web browser or MS Word.
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