简体   繁体   English

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

[英]Export html table to Excel file using ASP.NET MVC

I want to export my string html table to excel. 我想将我的字符串html表导出为ex​​cel。 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 发送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? 有人有解决方案吗?

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/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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