C# 在WebAPI中将HttpResponseMessage作为excel文件返回时出现问题
我已经创建了WebAPI,它使用closedxml nuget返回一个excel文件。基本上,它将我的C# 在WebAPI中将HttpResponseMessage作为excel文件返回时出现问题,c#,excel,asp.net-web-api,closedxml,C#,Excel,Asp.net Web Api,Closedxml,我已经创建了WebAPI,它使用closedxml nuget返回一个excel文件。基本上,它将我的数据表转换为excel。我指的是下面的几个链接 问题:在服务器路径上生成的excel没有问题。但是,当我通过webAPI以HttpResponseMessage的形式返回相同的文件进行下载时,excel文件已损坏。它说,“文件已损坏,无法打开”:( 我的代码: [System.Web.Http.AcceptVerbs("GET", "POST")] public HttpR
数据表
转换为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文件已损坏。无法解决问题。。
感谢您的帮助!!:)我看到的一个问题是:
var stream = new FileStream(path, FileMode.Open);
您正在发送文件流。您可以尝试使用字节[]
:
byte[] excelData = File.ReadAllBytes(path);
result.Content = new StreamContent(excelData);
你可以试试这个。试试这个:
[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;
}
}
你最终解决了这个问题吗?我也遇到同样的问题。更不用说防火墙的其他RFC合规性问题了,它对返回的内容长度不满意。不幸的是,这是swagger UI否定包的问题!:(result.Content=new StreamContent(excelData);StreamContent required System.IO.StreamMaybe:new ByteArrayContent(excelData);