目标是在内存中创建一个excel文件,并使用ASP.Net Core内置的API在浏览器中下载该文件,但是将excel保存为流并将其转换为字节数组,然后在excel上打开(Office 365版本1803)给出错误: 代码字节数组:
public IActionResult Export()
{
byte[] bytes;
MemoryStream stream = new MemoryStream();
using (ExcelPackage package = new ExcelPackage(stream))
{
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Employee");
//First add the headers
worksheet.Cells[1, 1].Value = "ID";
worksheet.Cells[1, 2].Value = "Name";
worksheet.Cells[1, 3].Value = "Gender";
worksheet.Cells[1, 4].Value = "Salary (in $)";
//Add values
worksheet.Cells["A2"].Value = 1000;
worksheet.Cells["B2"].Value = "Jon";
worksheet.Cells["C2"].Value = "M";
worksheet.Cells["D2"].Value = 5000;
worksheet.Cells["A3"].Value = 1001;
worksheet.Cells["B3"].Value = "Graham";
worksheet.Cells["C3"].Value = "M";
worksheet.Cells["D3"].Value = 10000;
worksheet.Cells["A4"].Value = 1002;
worksheet.Cells["B4"].Value = "Jenny";
worksheet.Cells["C4"].Value = "F";
worksheet.Cells["D4"].Value = 5000;
bytes = package.GetAsByteArray();
}
return File(bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "test.xlsx");
}
更新:添加了内存流示例
代码存储流:
public IActionResult Export()
{
using (ExcelPackage package = new ExcelPackage())
{
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Employee");
//First add the headers
worksheet.Cells[1, 1].Value = "ID";
worksheet.Cells[1, 2].Value = "Name";
worksheet.Cells[1, 3].Value = "Gender";
worksheet.Cells[1, 4].Value = "Salary (in $)";
//Add values
worksheet.Cells["A2"].Value = 1000;
worksheet.Cells["B2"].Value = "Jon";
worksheet.Cells["C2"].Value = "M";
worksheet.Cells["D2"].Value = 5000;
worksheet.Cells["A3"].Value = 1001;
worksheet.Cells["B3"].Value = "Graham";
worksheet.Cells["C3"].Value = "M";
worksheet.Cells["D3"].Value = 10000;
worksheet.Cells["A4"].Value = 1002;
worksheet.Cells["B4"].Value = "Jenny";
worksheet.Cells["C4"].Value = "F";
worksheet.Cells["D4"].Value = 5000;
var stream = new MemoryStream(package.GetAsByteArray());
return File(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "test.xlsx");
}
}
更新2 :使用.net core 2.1创建了一个新项目,该代码可以正常工作。这似乎是一个与项目相关的错误,以某种方式处理了请求的内容。要调查导致问题的原因并发布解决方案。
答案 0 :(得分:2)
我使用 package.Stream
而非package.GetAsByteArray
实现了类似的情况。
(这最后一个对我也失败了。)
请注意,我在您的代码中错过了 package.Save
。
(即使GetAsByteArray
,Package.Save
也会失败。)
public IActionResult Export()
{
MemoryStream content = new MemoryStream(); // Gets disposed by FileStreamResult.
using (ExcelPackage package = new ExcelPackage(content))
{
// Code to create the content goes here.
package.Save();
}
content.Position = 0;
return new FileStreamResult(content, "application/octet-stream") {
FileDownloadName = "test.xlsx"
};
}