[OpenXml] Generate excel in memory and dump to file

3200 단어 memory
public static void GenerateExcelFromStream()

{

    using (MemoryStream memoryStream = new MemoryStream()) {

        using (SpreadsheetDocument document = SpreadsheetDocument.Create(memoryStream, SpreadsheetDocumentType.Workbook)) {

            document.AddWorkbookPart();

            document.WorkbookPart.Workbook = new Workbook();



            document.WorkbookPart.AddNewPart<WorksheetPart>();

            document.WorkbookPart.WorksheetParts.First().Worksheet = new Worksheet();

            document.WorkbookPart.WorksheetParts.First().Worksheet.AppendChild(new SheetData());



            Row row = new Row();

            row.AppendChild<Cell>(new Cell() { CellValue = new CellValue("hahaasdfhkasddjjalsdkjflaksdjfladskjflj"), DataType = CellValues.String, CellReference = "A1" });

            document.WorkbookPart.WorksheetParts.First().Worksheet.First().AppendChild(row);

            document.WorkbookPart.WorksheetParts.First().Worksheet.Save();



            document.WorkbookPart.Workbook.AppendChild(new Sheets());

            document.WorkbookPart.Workbook.GetFirstChild<Sheets>().AppendChild(new Sheet() {

                Id = document.WorkbookPart.GetIdOfPart(document.WorkbookPart.WorksheetParts.First()),

                SheetId = 1,

                Name = "sheet1"

            });

            document.WorkbookPart.Workbook.Save(); 

        }



        using (FileStream fileStream = File.Create("generateExcel.xlsx")) {

            memoryStream.WriteTo(fileStream);

        }

    }

}

좋은 웹페이지 즐겨찾기