使用ASP.NET MVC将html表导出到Excel文件

时间:2022-09-25 09:56:54

I want to export my string html table to excel. When trying to export and when I click save I get the following exception

我想将我的字符串html表导出为ex​​cel。尝试导出时,单击“保存”时出现以下异常

The server can not add the header after sending the HTTP headers

发送HTTP标头后,服务器无法添加标头

This is my html table :

这是我的html表:

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:

当我点击继续时,我得到一个包含HTML代码的excel文件:

<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?

有人有解决方案吗?

1 个解决方案

#1


1  

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/

从这里:http://www.codescratcher.com/asp-net/export-html-excel-asp-net/

#1


1  

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/

从这里:http://www.codescratcher.com/asp-net/export-html-excel-asp-net/