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.
Related
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();
}
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/
I am working on asp.net 4.0 web application development using c#. I am trying to export the Gridview data to ms word document. I have used the following code.
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=MyWord.doc");
Response.ContentEncoding = System.Text.Encoding.UTF7;
Response.ContentType = "application/vnd.word";
System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
this.GridView1.RenderControl(oHtmlTextWriter);
Response.Output.Write(oStringWriter.ToString());
Response.Flush();
Response.End();
The application is running without problems but it returns the data in word like
+ADw-div+AD4- +ADw-table cellspacing+AD0AIg-0+ACI- cellpadding+AD0AIg-4+ACI- id+AD0AIg-GridView1+ACI- style+AD0AIg-color:+ACM-333333+ADs-border-collapse:collapse+ADsAIgA+- +ADw-tr style+AD0AIg-color:White+ADs-background-color:+ACM-507CD1+ADs-font-weight:bold+ADsAIgA+- +ADw-th scope+AD0AIg-col+ACIAPg-FileId+ADw-/th+AD4APA-th scope+AD0AIg-col+ACIAPg-PortalId+ADw-/th+AD4APA-th scope+AD0AIg-col+ACIAPg-FileName+ADw-/th+AD4APA-th scope+AD0AIg-col+ACIAPg-Extension+ADw-/th+AD4APA-th scope+AD0AIg-col+ACIAPg-Size+ADw-/th+AD4APA-th scope+AD0AIg-col+ACIAPg-Width+ADw-
I know it is much similar to html but how could i convert this into actual one. guide me.
this is works for me it requires itextsharp.dll
string FName = "filename.doc";
mygrid.AllowPaging = false;
mygrid.DataSource = datasource();
mygrid.DataBind();
Response.ClearContent();
Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", FName));
Response.Charset = "";
Response.ContentType = "application/ms-word";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
mygrid.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
I'm using following method to download a file.on a button click inside a iframe.it's working fine in every browser except IE.can some one plz suggest me a sollution
private void DownloadToBrowser(string filePath)
{
try
{
FileInfo file = new FileInfo(filePath);
Context.Response.Clear();
Context.Response.ClearHeaders();
Context.Response.ClearContent();
Context.Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
Context.Response.AddHeader("Content-Length", file.Length.ToString());
Context.Response.ContentType = "text/plain";
Context.Response.Flush();
Context.Response.TransmitFile(file.FullName);
Context.Response.End();
}
catch (Exception ex)
{
throw ex;
}
}
I would suggest removing the Context.Response.Flush(); line... I don't think it's necessary (as it will happen as part of Context.Response.End(); line), and maybe messing up how the browser receives the file on the next line.
Also, is the file you're transmitting definitely a plain-text file? If not, you'll need to provide a different Context.Response.ContentType();
You have most probably missed some HTTP response headers required by IE.
There is KB on microsoft web.
Also take a look at similar question on SO : PHP script to download file not working in IE
You could try something like this :
Context.Response.Buffer = true;
Context.Response.ContentType = "application/pdf";
Context.Response.AddHeader("Content-Disposition", "attachment;filename=" + FileName );
Context.Response.OutputStream.Write(dataBytes ,0,FileContentLength);
Also try adding this to your aspx page :
<%# Page aspCompat="True" other attributes %>
For Understanding I m using Dataset,
For download as a Excel File
Use Namespace:
using System.IO;
using System.Data;
DataSet ds = new DataSet("Table");
ds.Tables.Add("Table1");
ds.Tables[0].Columns.Add("Field1");
ds.Tables[0].Columns.Add("Field2");
ds.Tables[0].Columns.Add("Field3");
ds.Tables[0].Rows.Add();
ds.Tables[0].Rows[0][0] = "1";
ds.Tables[0].Rows[0][1] = "2";
ds.Tables[0].Rows[0][2] = "3";
HttpResponse response = HttpContext.Current.Response;
// first let's clean up the response.object
response.Clear();
response.Charset = "";
// set the response mime type for excel
response.ContentType = "application/vnd.ms-excel";
response.AddHeader("Content-Disposition", "attachment;filename=sample.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);
response.Write(sw.ToString());
response.End();
}
}
For Download as a Word File
Replace
response.ContentType = "application/msword";
response.AddHeader("Content-Disposition", "attachment;filename=sample.doc");
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