[OpenXml] Generate excel in memory and dump to file

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

 

posted @ 2015-07-27 13:26  webglcn  阅读(218)  评论(0编辑  收藏  举报