码迷,mamicode.com
首页 > 其他好文 > 详细

[OpenXml] Generate excel in memory and dump to file

时间:2015-07-27 14:52:39      阅读:135      评论:0      收藏:0      [点我收藏+]

标签:

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

 

[OpenXml] Generate excel in memory and dump to file

标签:

原文地址:http://www.cnblogs.com/webglcn/p/4679899.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!