Reputation: 1
Here is my code:
public IActionResult DownloadMyFile(int Id)
{
var fileData = // Service call to get data
using (var workbook = new XLWorkbook())
{
var worksheet = workbook.AddWorksheet("data");
var columnNames = fileData[0].GetType().GetProperties();
var currentColumn = 1;
foreach (var name in columnNames)
{
worksheet.Cell(1, currentColumn).Value = name.Name;
currentColumn++;
}
worksheet.Cell(2, 1).InsertData(fileData);
using (var stream = new MemoryStream())
{
workbook.SaveAs(stream);
var content = stream.ToArray();
return File(content,
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"MyFile.xlsx");
}
}
}
I am using ClosedXML to put the data into an excel sheet. Then I save "worksheet" in a stream and convert it to a binary array and return that in a FileContentResult
.
For context this lives in a controller in an Umbraco project
When I run my code and call this method, it returns an excel file with the correct name. But when I open the file, there is no data in it. I can't figure out why. When I debug my code, I can see that 'content' does have data in it. Any idea what's going on here?
I've tried changing the type to application/octect-stream
which changed nothing.
I've also tried changing the return type to HttpResponseMethod
but that has no effect either.
Upvotes: 0
Views: 365
Reputation: 2316
Set the position in the stream to 0 prior to attempting to return it.
e.g.:
using (var stream = new MemoryStream())
{
workbook.SaveAs(stream);
stream.Seek(0, SeekOrigin.Begin);
return File(stream,
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"MyFile.xlsx");
}
Upvotes: 1