export data to gridview from excel - asp.net

Response.ClearContent();
Response.AppendHeader("content.disposition", "attachment;filename=check.xls");
Response.ContentType = "application/ms-excel";
StringWriter strwriter = new StringWriter();
HtmlTextWriter htmlwriter = new HtmlTextWriter(strwriter);
GridView2.RenderControl(htmlwriter);
Response.Write(strwriter.ToString());
Response.End();
I 'm trying to import data to excel all the code is executing well but nothing is happing no file is generating, please help me I'm stuck.

It should work if you change content.disposition for content-disposition:
Response.AppendHeader("content-disposition", "attachment;filename=check.xls");
Two additional settings are also required:
1) Event validation must be deactivated at the page level:
<%# Page EnableEventValidation="false" ... %>
2) The following page function must be overridden (it can stay empty):
public override void VerifyRenderingInServerForm(Control control)
{
}

Related

How to remove a Gridview from an ASPX page?

I have an Aspx page that displays a GridView. The gridview would appear with data that was depending on which catergory was selected from a drop down menu. The user has the option to then download this as a CSV file (export to CSV). I now want the Gridview not to appear (beacuse it is so large it often just hangs) but instead to be able to download a CSV file with the data from the gridview. I have successfully built the button allowing for the download of this data by clicking the button. However, I now cannot open the page without the gridView appearing. I tried to comment out the Gridview code - this just broke the page. I tried to set the gridview as Visible="False" but this did not work either. What else can I do to prevent the gridview from appearing and the user to be taken straight to a download dialogue box?
wrap your Gridview to a div and set it to display:none in asp.net code –
Ex: <div id="divhidegrid" runat="server" style="display:none;" > <asp:GridView ID="gvtest" runat="server" > </div> like this
You can load your data in DataSet or DataTable from Code Behind and then export it directly to Excel/CSV without assigning it to GridView such as in the following example to export it to Excel:
Public Sub ExportToExcel(dt As DataTable)
If dt.Rows.Count > 0 Then
Dim tw As New System.IO.StringWriter()
Dim hw As New System.Web.UI.HtmlTextWriter(tw)
Dim dgGrid As New DataGrid()
dgGrid.DataSource = dt
dgGrid.DataBind()
'Get the HTML for the control.
dgGrid.RenderControl(hw)
'Write the HTML back to the browser.
Response.ContentType = "application/vnd.ms-excel"
Response.AppendHeader("Content-Disposition", "attachment; filename=Data.xls")
Me.EnableViewState = False
Response.Write(tw.ToString())
Response.[End]()
End If
End Sub
If you get errors like control must be placed in inside of form tag you may also be required put the following code in your backend (Reference: export-data-to-excel-from-datatable-gridview-aspnet-csharp)
Public Sub VerifyRenderingInServerForm(control As Control)
' Verifies that the control is rendered
End Sub
C# Version of above code:
public void ExportToExcel(DataTable dt)
{
if (dt.Rows.Count > 0) {
System.IO.StringWriter tw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
DataGrid dgGrid = new DataGrid();
dgGrid.DataSource = dt;
dgGrid.DataBind();
//Get the HTML for the control.
dgGrid.RenderControl(hw);
//Write the HTML back to the browser.
Response.ContentType = "application/vnd.ms-excel";
Response.AppendHeader("Content-Disposition", "attachment; filename=Data.xls");
this.EnableViewState = false;
Response.Write(tw.ToString());
Response.End();
}
}
public void VerifyRenderingInServerForm(Control control)
{
// Verifies that the control is rendered
}

Export pie chart to powerpoint using c#

i am trying to Export a pie chart to powerpoint slide uisng c# but not found any similar article which can help me...
please provide me some example or provide some useful link which can help me in achieving this functionality easily...
thanks,
Aman
we are using hipdf library but this is paid and we are converting html to image first and then showing this image on ppt slide. You can also do it by using inkscape exe file
In button_click event write following code.
GridView1.AllowPaging = false; //write this code only if paging is enabled.
GridView1.DataBind(); //write this code only if paging is enabled.
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=FileName.ppt");//for text file write FileName.txt
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.ppt";\\for text file write vnd.txt
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();
GridView1.AllowPaging = true; //write this code only if paging is enabled.
GridView1.DataBind();//write this code only if paging is enabled.
You will have to override function of VerifyRenderingInServerForm like this
public override void VerifyRenderingInServerForm(Control control)
{
//Keep it empty
}
And to avoid exception you have to set property of
<%# Page Language="C#" EnableEventValidation="false" %>

RegisterForEventValidation can only be called during Render

I have a webmethod which will be called from jquery ajax:
[WebMethod]
public string TestMethod(string param1, string param2)
{
StringBuilder b = new StringBuilder();
HtmlTextWriter h = new HtmlTextWriter(new StringWriter(b));
this.LoadControl("~/Pages/Controls/Listing.ascx").RenderControl(h);
string controlAsString = b.ToString();
return controlAsString;
}
(it's a non-static method and we are able to hit it. That's not an issue)
When the loadControl() method is executed, I get an error saying: RegisterForEventValidation can only be called during Render.
I have already included EnableEventValidation="false" for the current aspx, disabled viewstate also. but still i get the same error. Any ideas on this?
Solution is to disable the Page's Event Validation as
<%# Page ............ EnableEventValidation="false" %>
and Override VerifyRenderingInServerForm by adding following method in your C# code behind
public override void VerifyRenderingInServerForm(Control control)
{
/* Confirms that an HtmlForm control is rendered for the specified ASP.NET
server control at run time. */
}
Refer the Below Link
http://www.codeproject.com/Questions/45450/RegisterForEventValidation-can-only-be-called-duri
As per Brian's second link, without hopping further, just do this:
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
Html32TextWriter hw = new Html32TextWriter(sw);
Page page = new Page();
HtmlForm f = new HtmlForm();
page.Controls.Add(f);
f.Controls.Add(ctrl);
// ctrl.RenderControl(hw);
// above line will raise "RegisterForEventValidation can only be called during Render();"
HttpContext.Current.Server.Execute(page, sw, true);
Response.Write(sb);
You need to notify ASP.Net that not to validate the event by setting the EnableEventValidation flag to false.
You can set it in the Web.Config in the following way
<%# Page Language="C#" AutoEventWireup="true" EnableEventValidation = "false"

Export a data set to Excel and raise a file download dialog from an asp.net web method

I am using the following code to export a data set to an Excel sheet.
[WebMethod]
public static void ExporttoExcel()
{
DataSet ds;
productfactory pf=new productfactory();
ds = pf.getproducts();
HttpResponse response = HttpContext.Current.Response;
// first let's clean up the response.object
response.Clear();
response.Charset = "";
response.ContentEncoding = System.Text.Encoding.Default;
// set the response mime type for excel
response.ContentType = "application/vnd.ms-excel";
response.AddHeader("Content-Disposition", "attachment;filename=\"products.xls\"");
// create a string writer
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
// instantiate a datagrid
DataGrid dg = new DataGrid();
dg.DataSource = ds.Tables[0];
dg.DataBind();
dg.RenderControl(htw);
string filepath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\products.xls";
response.Write(sw.ToString());
// response.End();
}
}
}
The problem is that it's not raising file download and hence no export is taking place. The same code works fine in a normal method. But with the web method it's not working.
I suggest to make an HttpHandler ending in ashx, and place inside him your code that create the excel file.
then call it from your javascript code like that.
document.location.href = "ExporttoExcel.ashx";
The problem is that WebMethods are not designed to allow you to interact with the Response object (evident in that it wasn't available and you had to use HttpContext.Current.Response to get to it). WebMethods are designed to be blackbox to the user. They will perform and action and/or return a value.
Perhaps you can give us a better idea of what you are trying to accomplish and we can suggest an alternate solution.
u can use to create a dynamic iframe with URL set to the Web Handler to generate the Excel this will raise the file download with out posting the current page.

Export Gridview with image to Excel - Problem

I have a Gridview in my ASP.NET C# Page. It has a couple of columns and also one image column. I can export the entire columns to an Excel file, but the image column is blank. By the way, I use the full path.
Any Idea?
Yes in default.aspx (For local Export)
ImageUrl="http://localhost:4056/CSharp/banner.gif"
instead of ImageUrl="~/banner.gif"
or (For remote Export)
http://your ip address here :port/foldername/filename
Response.Clear(); //this clears the Response of any headers or previous output
Response.Buffer = true; //make sure that the entire output is rendered simultaneously
Response.ContentType = "application/vnd.ms-excel";
StringWriter stringWriter = new StringWriter(); //System.IO namespace should be used
HtmlTextWriter htmlTextWriter = new HtmlTextWriter(stringWriter);
GridView2.GridLines = GridLines.Both;
GridView2.RenderControl(htmlTextWriter);
Response.Write(stringWriter.ToString());
Response.End();

Resources