Skip to content
This repository was archived by the owner on Nov 24, 2020. It is now read-only.
This repository was archived by the owner on Nov 24, 2020. It is now read-only.

create a new xlsx and write to memory stream #171

@livioco

Description

@livioco

I have to create a new xlsx from server side (without save it on server side), but I have to download the file on client side.

I have this error " Cannot access a closed Stream"

This is the code. Any suggestions?

[HttpGet]
public async Task DownloadXLS()
{
try
{

            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);

            using (var memoryStream = new MemoryStream()) //creating memoryStream
            {
                workbook.Write(memoryStream);

                return File(memoryStream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "test.xlsx");
            }

        }
        catch(Exception ex)
        {
            return null;

        }


    }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions