Cannot export to Excel in IE 11 - asp.net

I have a web application that exports data from a gridview to Excel. It works fine in Chrome but doesn't work in IE 11 and Firefox. I see a lot of issues with this when I google it but this error seems to be unique.
protected void ExportToExcel(List<MapAmericas.Model.Project> Projects)
{
Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/vnd.ms-excel";
Response.ContentEncoding = System.Text.Encoding.Unicode;
Response.AddHeader("content-disposition", "attachment;filename=MyFile" + DateTime.Now.ToString() + ".xls");
Response.Charset = "";
Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());
this.EnableViewState = false;
System.IO.StringWriter sw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw);
GridView gv = new GridView();
gv.AutoGenerateColumns = false;
gv.RowDataBound += new GridViewRowEventHandler(dataExportExcel_ItemDataBound);
gv.DataSource = Projects;
gv.DataBind();
gv.RenderControl(htw);
Response.Write(AddExcelStyling()); //this contains the opening html elements
StringBuilder sbResponseString = new StringBuilder();
sbResponseString.Append(sw + "</body></html>");
Response.Write(sbResponseString.ToString());
Response.Flush();
Response.Close();
Response.End();
}
...and the issue I'm getting has to do with not being able to access Temporary Internet Files. I get a popup "Problems during Load" and about a dozen entries: "Missing File...Temporary Internet Files\Content\" and then I get a message reading "Unable to read file".
I had an image to represent the error but I'm not able to upload images.
When I click on one of the links, it loads up my webpage without any styles and I don't get an excel file.
Does anyone know what the issue would be?

I got it! I added 2 lines of code to my existing code and it works. See lines marked with **:
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Buffer = true;
//HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.Unicode;
HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=Panorama_Project-" + DateTime.Now.ToString() + ".xls");
HttpContext.Current.Response.Charset = "";
HttpContext.Current.Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());
this.EnableViewState = false;
System.IO.StringWriter sw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw);
GridView gv = new GridView();
gv.AutoGenerateColumns = false;
gv.RowDataBound += new GridViewRowEventHandler(dataExportExcel_ItemDataBound);
gv.DataSource = Projects;
gv.DataBind();
gv.RenderControl(htw);
HttpContext.Current.Response.Write(AddExcelStyling());
StringBuilder sbResponseString = new StringBuilder();
sbResponseString.Append(sw + "</body></html>");
**HttpContext.Current.Response.AddHeader("Content-Length", sbResponseString.Length.ToString());**
HttpContext.Current.Response.Write(sbResponseString.ToString());
//HttpContext.Current.Response.Flush();
//HttpContext.Current.Response.Close();
//HttpContext.Current.Response.End();
**System.Web.HttpContext.Current.ApplicationInstance.CompleteRequest();**
It seems as though it was trying to display the entire Response object which included my page and all linked resources. The Content-Length and replacing Reponse.End and Response.Flush with System.Web.HttpContext.Current.ApplicationInstance.CompleteRequest() seems to do the trick.

This is the simplified version of an Export To Excel function (for a datatable) that I use and one that works for all the browsers. See if this helps. The code is quite similar to yours though:
public void ExportDataToExcel(String FileName, DataTable dtData)
{
// get gridview out of datatable
GridView gv = new GridView();
gv.AllowPaging = false;
gv.DataSource = dtData;
gv.DataBind();
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.AddHeader("content-disposition",
"attachment;filename=" + FileName + ".xls");
HttpContext.Current.Response.Charset = "";
HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
for (int i = 0; i < gv.Rows.Count; i++)
{
// Apply text style to each Row
gv.Rows[i].Attributes.Add("class", "textmode");
}
gv.RenderControl(hw);
HttpContext.Current.Response.Output.Write(sw.ToString());
// commenting this out to resolve this error
// System.Web.HttpException: The remote host closed the connection.
// The error code is 0x800703E3.
// HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
}

Related

Gridview paging doesn't work after export

I have a gridview with paging and sorting allowed, which I'm exporting to an excel file as follows.
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);
GridView1.AllowPaging = false;
GridView1.AllowSorting = false;
GridView1.DataBind();
GridView1.RenderControl(hw);
Response.Write(style);
Response.Output.Write(sw.ToString());
GridView1.AllowPaging = true;
GridView1.AllowSorting = true;
GridView1.DataBind();
Response.Flush();
Response.End();
After the export, the paging and rowcommands are not working. When I click on a page index or a link in a row, the excel file is downloaded again. Can anyone suggest how to resolve this issue?
Thanks.

Download Gridview Error data

I am working on a project, where I want to download gridview row data, but it is not working for me. Here is the code i used for download:
string fileName = "chhattisgarhishafte" + DateTime.Now.ToString() + ".doc";
GridView1.DataSource = dtD;
GridView1.DataBind();
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=" + fileName);
Response.Charset = "";
Response.ContentType = "application/vnd.ms-word ";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView1.AllowPaging = false;
GridView1.DataBind();
GridView1.RenderBeginTag(hw);
GridView1.RenderControl(hw);
Response.Output.Write(sw.ToString());
GridView1.RenderEndTag(hw);
Response.Flush();
Response.End();
stD is datatble which stores the gridview selected rows.
The errror is:
Control 'ctl00_ContentPlaceHolder1_GridView1' of type 'GridView' must be placed inside a form tag with runat=server.
Please use in form tag in the master page use runat="server"
use this code,its working in my application
if (gv.Rows.Count > 0)
{
StringWriter tw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(tw);
//Get the HTML for the control.
gv.RenderControl(hw);
//Write the HTML back to the browser.
//Response.ContentType = application/vnd.ms-excel;
Response.ContentType = "application/vnd.ms-excel";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + strFileName);
EnableViewState = false;
Response.Write(tw.ToString());
Response.End();
}

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.

Passing a grid to a function used to export to excel

I have a method that is used to export the data to excel.Till now I have been passing table to the method.But now I wish to pass the grid data so that I do not have to call the procedures for different instances for getting different filtered data sets.
is there a way to do so?
public void ExportToExcel(DataSet ds)
{
if (ds.Tables[0].Rows.Count > 0)
{
string filename = ds.Tables[1].Rows[0]["filename"].ToString() + ".xls";
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 = ds.Tables[0];
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.Clear();
Response.ClearHeaders();
Response.Charset = "";
Response.AddHeader("content-disposition", String.Concat("attachment;filename=", filename));
Response.AddHeader("Cache-Control", "max-age=0");
Response.ContentType = "application/vnd.xls";
// this.EnableViewState = false;
Response.Write(tw.ToString());
Response.End();
}
}
This is the method that I am using to export to excel.

How to export an mschart chart to excel?

I have created a chart with Mschart.I want to export the created chart to excel.
I'm using following code but when I open it in excel I just see some unknown code instead of chart.
using (var chartimage = new MemoryStream())
{
ChartAmalkerd.SaveImage(chartimage, ChartImageFormat.Png);
ExportToExcel(chartimage.GetBuffer());
}
private void ExportToExcel(byte[] input)
{
string attachment = "attachment; filename=Employee.xls";
Response.ClearContent();
Response.ContentEncoding = Encoding.GetEncoding(1256);
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/vnd.ms-excel";
Response.Buffer = true;
this.EnableViewState = false;
Response.BinaryWrite(input);
Response.Flush();
Response.Close();
Response.End();
}
I have found the same issue and after making several attempts, I was able to find out the correct way. This worked for me and the code is as follows.
string tmpChartName = "test2.jpg";
string imgPath = HttpContext.Current.Request.PhysicalApplicationPath + tmpChartName;
Chart1.SaveImage(imgPath);
string imgPath2 = Request.Url.GetLeftPart(UriPartial.Authority) + VirtualPathUtility.ToAbsolute("~/" + tmpChartName);
Response.Clear();
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", "attachment; filename=test.xls;");
StringWriter stringWrite = new StringWriter();
HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
string headerTable = #"<Table><tr><td><img src='" + imgPath2 + #"' \></td></tr></Table>";
Response.Write(headerTable);
Response.Write(stringWrite.ToString());
Response.End();
Hope this helps.
I also came across such scenario in one of my project.
Here is the solution.
http://haseet.blogspot.in/2013/02/develop-chart-in-aspnet-with-export-to-excel-pdf-msoffice-openoffice.html
Add this code for your globalization, this works for me.
Dim info As System.Globalization.CultureInfo = New System.Globalization.CultureInfo("en-US")
Thread.CurrentThread.CurrentCulture = info
Thread.CurrentThread.CurrentUICulture = info
context.Response.ContentEncoding = System.Text.Encoding.UTF8
context.Response.HeaderEncoding = System.Text.Encoding.UTF8

Resources