简体   繁体   中英

Export html table to Excel file using ASP.NET MVC

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?

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM