问题
I have created WebAPI which returns an excel file using closedxml nuget. Basically it converts my DataTable
to excel. I'm referring couple of links below,
How to return a file (FileContentResult) in ASP.NET WebAPI
Returning binary file from controller in ASP.NET Web API
Issue : excel generated on server path has NO issues. But when I download the same by returning it as HttpResponseMessage
via webAPI the excel file is corrupted. It says, "The file is corrupt and cannot be opened" :(
My Code :
[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;
}
}
The generated excel on server has no issues. Only the downloaded excel file via webAPI is corrupted. Unable to figure out the issue.. any help appreciated!! :)
回答1:
Try this:
[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;
}
}
回答2:
One issue I am seeing is that :
var stream = new FileStream(path, FileMode.Open);
you are sending FileStream. Instead of this, you can try with byte []
:
byte[] excelData = File.ReadAllBytes(path);
result.Content = new StreamContent(excelData);
You can give a try with this.
来源:https://stackoverflow.com/questions/41200744/issue-with-returning-httpresponsemessage-as-excel-file-in-webapi