【发布时间】: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