Export html table to Excel file using ASP.NET MVC
12,044
You might want to use the codes below. Hopefully, it works.
Response.ClearContent();
Response.ClearHeaders();
Response.BufferOutput = true;
Response.ContentType = "application/excel";
Response.AddHeader("Content-Disposition", "attachment; filename=Reliquat.xslx");
Response.Write(tab);
Response.Flush();
Response.Close();
Response.End();
From here: http://www.codescratcher.com/asp-net/export-html-excel-asp-net/
Author by
Sarra
Updated on July 17, 2022Comments
-
Sarra almost 2 years
I want to export my string html table to excel. When trying to export and when I click save I get the following exception
The server can not add the header after sending the HTTP headers
This is my html table :
string tab = "<table cellpadding='5' style='border:1px solid black; border-collapse:collapse'>"; tab += "<tr><td style=' border-width:1px;border-style:solid;border-color:black;'>NumClient</td><td style=' border-width:1px;border-style:solid;border-color:black;'>Raison Sociale</td></tr>"; tab += "<tr><td style='border-width:1px;border-style:solid;border-color:black;'>" + NumClient + "</td><td style='border-width:1px;border-style:solid;border-color:black;'>" + Rs + "</td><td style='border-width:1px;border-style:solid;border-color:black;text-align:right;'> </td></tr>"; tab += "</table>";
This is Controller code :
Response.ClearContent(); Response.AddHeader("Content-Disposition", "attachment; filename=Reliquat.csv"); Response.ContentType = "text/csv"; Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8"); Response.Write(tab); Response.End();
And when I click continue I get an excel file that contains html code:
<table cellpadding='5' style='border:1px solid black; border-collapse:collapse'>"; tab += "<tr><td style=' border-width:1px;border-style:solid;border-color:black;'>NumClient</td><td style=' border-width:1px;border-style:solid;border-color:black;'>Raison Sociale</td></tr>
Does anyone have a solution for this?
-
Jernej Pirc almost 8 yearsThis is Web Forms sample but you can change it to work with MVC
-
Sarra almost 8 yearsThanks Jernej , but I don't understand webForms very well ,Have you an example with MVC ? :)
-
Sarra almost 8 yearswhen I tried the code bellow , I got the following exception : Remote host closed the connection. The error code is 0x80070057.
-
Sarra almost 8 yearsI got the first exception : The server can not add the header after sending the HTTP headers
-
Sarra almost 8 yearsI solved the problem by deleting @Html.AntiForgeryToken() but I did'nt understand why
-
Venugopal M about 7 yearsPresume you incorrectly mentioned "Reliquat.xslx" whilst the correct one is Reliquat.xlsx / xls