使用NPIO制作Excel,然后使用FileStreamResult发送回去吗?

问题描述 投票:0回答:1

我正在尝试制作一个excel文件,然后通过FileStreamResult将其发送回。我正在使用asp.net core

我开始使用NIPO示例

var newFile = @"newbook.core.xlsx";

            var fs = new MemoryStream();


                IWorkbook workbook = new XSSFWorkbook();

                ISheet sheet1 = workbook.CreateSheet("Sheet1");

                sheet1.AddMergedRegion(new CellRangeAddress(0, 0, 0, 10));
                var rowIndex = 0;
                IRow row = sheet1.CreateRow(rowIndex);
                row.Height = 30 * 80;
                row.CreateCell(0).SetCellValue("this is content");
                sheet1.AutoSizeColumn(0);
                rowIndex++;

                var sheet2 = workbook.CreateSheet("Sheet2");
                var style1 = workbook.CreateCellStyle();
                style1.FillForegroundColor = HSSFColor.Blue.Index2;
                style1.FillPattern = FillPattern.SolidForeground;

                var style2 = workbook.CreateCellStyle();
                style2.FillForegroundColor = HSSFColor.Yellow.Index2;
                style2.FillPattern = FillPattern.SolidForeground;

                var cell2 = sheet2.CreateRow(0).CreateCell(0);
                cell2.CellStyle = style1;
                cell2.SetCellValue(0);

                cell2 = sheet2.CreateRow(1).CreateCell(0);
                cell2.CellStyle = style2;
                cell2.SetCellValue(1);

                workbook.Write(fs);

但是似乎将其保存到我的项目解决方案中。

我也看到此错误

   <div class="titleerror">ObjectDisposedException: Cannot access a closed Stream.</div>
excel asp.net-core memorystream filestreamresult
1个回答
0
投票

根据您的代码,您可以使用正确的内容类型返回File

var newFile = @"newbook.core.xlsx";

var fs = new MemoryStream();


IWorkbook workbook = new XSSFWorkbook();

ISheet sheet1 = workbook.CreateSheet("Sheet1");

sheet1.AddMergedRegion(new CellRangeAddress(0, 0, 0, 10));
var rowIndex = 0;
IRow row = sheet1.CreateRow(rowIndex);
row.Height = 30 * 80;
row.CreateCell(0).SetCellValue("this is content");
sheet1.AutoSizeColumn(0);
rowIndex++;

var sheet2 = workbook.CreateSheet("Sheet2");
var style1 = workbook.CreateCellStyle();
style1.FillForegroundColor = HSSFColor.Blue.Index2;
style1.FillPattern = FillPattern.SolidForeground;

var style2 = workbook.CreateCellStyle();
style2.FillForegroundColor = HSSFColor.Yellow.Index2;
style2.FillPattern = FillPattern.SolidForeground;

var cell2 = sheet2.CreateRow(0).CreateCell(0);
cell2.CellStyle = style1;
cell2.SetCellValue(0);

cell2 = sheet2.CreateRow(1).CreateCell(0);
cell2.CellStyle = style2;
cell2.SetCellValue(1);

workbook.Write(fs);
MemoryStream memoryStream = new MemoryStream(fs.ToArray());
memoryStream.Position = 0;


return File(memoryStream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", newFile);
© www.soinside.com 2019 - 2024. All rights reserved.