Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.Net Export Data to Excel

Tags:

c#

asp.net

excel

Wondering what is a good library I can use with VS2005 to export data to a excel file. The file has some formatting like background colors and colspans.

Thanks

like image 777
MindGame Avatar asked Nov 30 '11 18:11

MindGame


People also ask

How do I export a table from Excel to ASP NET core?

using FileSaver. js plugin and TableExport plugin to export html table to excel. Right click the wwwroot folder, then click Add and Client-Side Library..., enter FileSaver. js and click the Install button to install the library.


1 Answers

Here is some code that uses a trick to output HTML to an Excel file. I have found that you can trick excel into opening an HTML by setting the content type of the output to "application/excel".

In the code below secresults is an HTML div like so:

<div id="secresults" runat="server" visible="false" class="secresults">
Content or data here.
</div>

In code behind:

Response.ClearContent();
string filename = "Output" + istartDate.ToShortDateString() + ".xls";
Response.AddHeader("content-disposition", "attachment; filename=" + filename + ";");
Response.ContentType = "application/excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);

secresults.RenderControl(htw);


Response.Write(sw.toString());
Response.End();

I have found that you can use some html formatting in excel. To test which formatting you can use you can create an html file and rename it to a .xls file, then open it with excel. You can get a pretty good idea about what HTML Excel will read.

like image 152
Matt Elliott Avatar answered Sep 28 '22 03:09

Matt Elliott