I am trying to export a gridview's contents to excel. I have some code:
public void ExcelDownload(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.Charset = "UTF-8";
Response.AppendHeader("Content-Disposition", "attachment;filename=MailingList.xls");
Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
Response.ContentType = "application/ms-excel";
this.EnableViewState = false;
System.Globalization.CultureInfo myCItrad = new System.Globalization.CultureInfo("EN-US", true);
System.IO.StringWriter oStringWriter = new System.IO.StringWriter(myCItrad);
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
MailingList.RenderControl(oHtmlTextWriter);
Response.Write(oStringWriter.ToString());
}
which runs when a link is clicked. This works fine, except that it is exporting the entire webpage, instead of just the gridview (MailingList). Does anyone know how to fix this?
Tehnically speaking this is not export to excel, but you send a html with a wrong headers to trick browser to open this content with excel. If you stick with this solution you have to render just GridView on separate aspx page.
This solution has may problems, excel it self will warn user that content is different from extension, becouse you send html and your response headers are saying that this is a excel file. And I can bet that some antimalware software on client or something similar on server, will block this response since serving different content than declared in headers is known malware behaviour.
Better use NPOI (xls) or / and EPPlus (xlsx) and fully control your excel export.
Related
I have a C#/asp.net program that stores data in a datagrid and then uses HttpResponse to create an Excel file from it. This worked well until Microsoft made security changes. Here's some information on that change: http://www.networksteve.com/exchange/topic.php/XLS_file_will_not_open_in_Excel_2016,_only_gray_view/?TopicId=77375&Posts=3. The solutions such as turning off Excel security and uninstalling the patch the caused the problem are not acceptable for my client. The official Microsoft answer is "The best option is to move away from using HTML wrapped as .XLS. If you use native formats (e.g. XLS, XLSX, XLSB) which will open in protected view when untrusted, this will provide some level of protection from the documents being opened." http://answers.microsoft.com/en-us/office/forum/office_2010-excel/windows-installed-updates-and-now-downloaded-excel/069b0fdf-d085-4322-b298-5976d0efa9ce?rtAction=1468539460673
My question is, how do I do that? I tried using the Microsoft.Interop and found multiple people saying this is not a good solution. I could never get that working anyway; see that discussion here: How can I download an Excel file to the user's download folder?
See my code below. I'm hoping that I can change the header or content type and get this to work. I'm open to any coding suggestions. As I said, our client is not going to change security options on their and their clients' machines; this needs to be something I can do in the code so the client doesn't have to do anything. Also, my boss is very hesitant to give me time to learn 3rd party controls so those are probably out as well.
var grid = new DataGrid();
grid.HeaderStyle.Font.Bold = true;
grid.AlternatingItemStyle.BackColor = System.Drawing.Color.DarkGray;
grid.DataSource = GetTable(storerId, bSunday, bMonday, bTuesday, bWednesday, bThursday, bFriday, bSaturday, beginDate, endDate);
grid.DataBind();
response.Clear();
//response.AddHeader("content-disposition", string.Format("{0}{1}{2}{3}{4}", "attachment;filename=", storerId, "KpiExport", DateTime.Today.ToShortDateString(), ".xls"));
//response.AddHeader("Content-Disposition", string.Format("{0}{1}{2}{3}{4}", "attachment;filename=", storerId, "KpiExport", DateTime.Today.ToShortDateString(), ".xls"));
HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "sample.xls"));
response.Charset = "";
// response.ContentType = "application/vnd.xls";
response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
var writer = new StringWriter();
var htmlWriter = new HtmlTextWriter(writer);
grid.RenderControl(htmlWriter);
response.Write(writer.ToString());
response.End();
I have to Provide the functionality to export all the data shown in repeater to excel file. I have successfully done that but the file size goes above 4MBs.
Here is the code I am using.
public void ExportToExcel(Repeater name)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=RepeaterExport.csv");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
Repeater rp = name;
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
foreach (RepeaterItem item in name.Items)
{
item.Controls.Remove(item.FindControl("hd_Depot"));
item.Controls.Remove(item.FindControl("hd_ProdCode"));
item.Controls.Remove(item.FindControl("hd_Closing"));
item.Controls.Remove(item.FindControl("hd_groupName"));
}
rp.RenderControl(hw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
Now when I use xls or xlsx it downloads perfectly but with large size but if I use csv it writes the whole html code to excel file. my main motive here is to shrink the size of the excel file to less than 1MB. Please advise.
It looks like you write an HTML or CSV file and pretends it is an Excel sheet in the Content-Type so that it opens with Excel. A better solution is to create a real Excel sheet, i.e. with an xlsx extension, using some library that can do this for you.
I think the xlsx contains the entire html, and that's why it's so big.
If you just want to export to csv:
create a string which contains the data (in your for loop)
Contenttype is: "text/csv"
I use a kbCSV and the CSVWriter.
Am getting an error when I export dynamically created html table to excel. the error says
Missing File: ~\Temporary Internet Files\Content.IE5\style.css.
when I say ok then the excel opens with the data displayed on browser. Don't know where am going wrong. Below is the code to excel export.
Response.ContentType = "application/x-msexcel";
Response.Clear();
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.AddHeader("Content-Disposition", "attachment; filename=ExcelFilenew.xls");
StringWriter tw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(tw);
HtmlTbl.RenderControl(hw);
Response.Write(tw.ToString());
Response.End();
You must do your export to XLS file and the whole XLS(x?) file creation on the server side.
This way as you do it you are probably trying to open HTML as XLS file at the client.
Create your XLSX file completely on the server side using some library like EPPlus and then send the resulting file to the client as a Response of ContentType = application/x-msexcel or better see this answer for what type of response you should use.
I am working on a web application which consists of some reports. These report is generated on a location wise data
The report should have a feature to be extracted to an excel file. For which I use render control.
private void ExprotToExcel()
{
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=ExportData.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
mainReport.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
}
The code works fine. Now the problem is that the user should also be able to export the report based on multiple locations. What I mean is that suppose there are 2 locations for which the report needs to be extracted. The report should be exported to the excel file directly in multiple sheets on the same workbook. I can use the above code to do that but I need multiple sheets and not multiple workbook.
Can anyone please guide me on the right path?
Edit : Forgot to mention that I have used multiple gridviews, data view and label controls on the webpage.
You can use a library for this:
http://epplus.codeplex.com/
Beware of NOT use Office Interop libraries in a web environment.
http://support.microsoft.com/kb/257757
So I am using this code, to export a formview to Word.
Its works great..But I want it to export to PDF so that it cannot be edited. Or may be to a word doc so that not body can make changes.
protected void Button1_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition",
"attachment;filename=Report.doc");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-word";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
FormView1.DataBind();
FormView1.RenderControl(hw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
The problem is, even when I change the content type and header element in the above code, it says that the output pdf has errors.
I really want to either convert the doc to pdf or generate pdf using this code.
Please help.
Thanks..
Your best bet to create PDFs in ASP.NET is to use a plug in like iTextSharp. I have used it in the past and it's very simple and free.
http://itextpdf.com/
As mentioned above, creating PDF using one of the existing libraries would be more efficient.
But if you're down to use interop, you can download save as pdf plugin for Microsoft Office.
And then pass "pdf" format to SaveAs method
Alternatively, you can apply several properties to your word document:
1. Mark as Final doc.Final = true;
2. Restrict editing
For newer version of Word, there's a Protect method, that provides a convenient way of restricting editing: http://msdn.microsoft.com/en-us/library/ms178793.aspx