Exporting Repeater Data to Excel in C# .net - c#

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.

Related

Exporting file gives me an error: Filename is in a different format than specified by the file extension

Here's the export piece of my code:
private void ExportGridView()
{
// Exports the data in the GridView to Excel
// First, fill the datagrid with the results of the session variable
DataTable gridDataSource = (DataTable)Session["SSRegisterSplit"];
DataGrid dgGrid = new DataGrid();
dgGrid.DataSource = gridDataSource;
dgGrid.DataBind();
// Exports the data in the GridView to Excel
string attachment = "attachment; filename=Claim_Details_" + LPI_ID + ".xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
dgGrid.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}
When it exports, it shows up in my footer automatically with an option to Open or Save.
If I choose "Open", Excel launches and then I get an error box:
The file you are trying to open, 'Claim_Details_1586.xls' is in a
different format than specified by the file extension. Verify that
the file is not corrupted and is from a trusted source before opening
the file. Do you want to open the file now?
If I choose 'Yes', it opens the file but not all the records are in it.
Any ideas on what's happening/how to fix it?
EDIT:
Putting a break point in the function, I noticed that when it gets to Response.End(); it throws the error:
Thread Was being Aborted.
I think this is what you want:
Is Response.End() considered harmful?
Don't use Response.End()
Consider using:
Response.Flush()
Response.SuppressContent = True
HttpContext.Current.ApplicationInstance.CompleteRequest()
—————————————————————————————
However. I'm pretty sure that the ”save an html file with .XLS extension” will always result in Excel showing an error.
The alternative is to pick something from http://nugetmusthaves.com/Tag/Excel to create a proper xls file. I've used EPPlus before but this page suggests that ClosedXML will do it for you in 5 lines.
If you aren't familiar with installing NuGet packages, then start here: https://learn.microsoft.com/en-gb/nuget/tools/package-manager-ui

Error during export to excel in asp.net c#

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.

MVC4: Export an .xlsx file to excel through mvc using chrome. It works for .xls but not .xlsx

How can I export an .xlsx file to excel through mvc using chrome. It works for .xls but not .xlsx
Response.ClearContent();
Response.AddHeader("content-disposition", "attachment; filename= Estimate1.xlsx");
Response.ContentType = "application/excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
Response.Write(sw.ToString());
Response.End();
and when i open excel file. it show like this. "Excel cannot open file 'FileName.xlsx' because the file format or file extension is not valid."
so much appreciated your help! :)
Try changing content type for .xlsx
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
You should use the correct MIME type. For DOCX is application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
See this blog post and this answer for more details

Export Doc to PDF Asp.net

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

GridView Export to Excel is exporting entire aspx page

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.

Categories