【问题标题】:Export html table to Excel file using ASP.NET MVC使用 ASP.NET MVC 将 html 表导出到 Excel 文件
【发布时间】:2016-05-20 18:40:30
【问题描述】:

我想将我的字符串 html 表导出到 excel。尝试导出并单击保存时,出现以下异常

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

这是我的 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>";

这是控制器代码:

 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(); 

当我点击继续时,我得到一个包含 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>

有人对此有解决方案吗?

【问题讨论】:

  • 内容类型不正确。您可能希望将其更改为 application/excel 并使用 Reliquat.xslx 作为文件名
  • 谢谢 Hatjhie,但我遇到了同样的错误
  • 好的。我认为下面发布的回复将能够回答您的问题。你可以试试看。
  • 将您的代码更改为:Response.ClearContent(); Response.ClearHeaders(); Response.BufferOutput = true; Response.ContentType = "应用程序/excel"; Response.AddHeader("Content-Disposition", "attachment; filename=Reliquat.xslx"); Response.Write(标签); Response.Flush();响应。关闭(); Response.End();
  • 不要使用 Response.End() stackoverflow.com/questions/1087777/…

标签: c# html asp.net-mvc


【解决方案1】:

您可能希望使用以下代码。希望它有效。

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();

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

【讨论】:

  • 这是 Web 表单示例,但您可以将其更改为与 MVC 一起使用
  • 谢谢 Jernej,但我不太了解 webForms,你有 MVC 的例子吗? :)
  • 当我尝试下面的代码时,我得到了以下异常:远程主机关闭了连接。错误代码为 0x80070057。
  • 我遇到了第一个异常:服务器在发送 HTTP 标头后无法添加标头
  • 我通过删除@Html.AntiForgeryToken() 解决了这个问题,但我不明白为什么
猜你喜欢
  • 2012-03-10
  • 1970-01-01
  • 1970-01-01
  • 2021-04-06
  • 2016-09-03
  • 1970-01-01
  • 2021-02-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多