【发布时间】:2016-12-17 16:36:06
【问题描述】:
我创建了 WebAPI,它使用 closedxml nuget 返回一个 excel 文件。基本上它将我的DataTable 转换为excel。我指的是下面的几个链接,
问题:在服务器路径上生成的 excel 没有问题。但是,当我通过 webAPI 将其返回为HttpResponseMessage 来下载相同的内容时,excel 文件已损坏。它说,“文件已损坏,无法打开”:(
我的代码:
[System.Web.Http.AcceptVerbs("GET", "POST")]
public HttpResponseMessage ExportExcel()
{
DataTable scoredRecords = Getdt();
if (scoredRecords.Rows.Count > 0)
{
var path = @"C:\Raghav\asdf.xlsx";
XLWorkbook wb = new XLWorkbook();
wb.Worksheets.Add(scoredRecords, "sample");
// excel getting generated on server properly-No issues.
wb.SaveAs(path);
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
var stream = new FileStream(path, FileMode.Open);
result.Content = new StreamContent(stream);
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "sample.xlsx"
};
result.Content.Headers.ContentLength = stream.Length;
//tried with "application/ms-excel" also
result.Content.Headers.ContentType =
new MediaTypeHeaderValue("application/octet-stream");
return result;
}
}
服务器上生成的excel没有问题。只有通过webAPI下载的excel文件损坏了。无法弄清楚问题.. 任何帮助表示赞赏! :)
【问题讨论】:
-
你最终解决了这个问题吗?我遇到了同样的问题。更不用说防火墙对返回的内容长度不满意的其他 RFC 合规性问题。
-
不幸的是,这是 swagger UI negate package 的问题! :(
标签: c# excel asp.net-web-api closedxml