我创建了 WebAPI,它使用 closexml nuget 返回一个 excel 文件。基本上它改变了我的DataTable
脱颖而出。我指的是下面的几个链接,
如何在 ASP.NET WebAPI 中返回文件 (FileContentResult)
从 ASP.NET Web API 中的控制器返回二进制文件
Issue :在服务器路径上生成的 excel 没有问题。但是当我通过将其返回为下载相同的内容时HttpResponseMessage
通过 webAPI,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 文件已损坏。无法弄清楚问题..
任何帮助表示赞赏! :)
尝试这个:
[HttpGet]
public HttpResponseMessage Export()
{
using (var wb = new XLWorkbook())
using (MemoryStream ms = new MemoryStream())
{
wb.Worksheets.Add("sample").FirstCell().SetValue("some value");
wb.SaveAs(ms);
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
result.Content = new ByteArrayContent(ms.GetBuffer());
result.Content.Headers.ContentLength = ms.Length;
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "sample.xlsx"
};
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
return result;
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)