var memoryStream = new MemoryStream(); using (var document = SpreadsheetDocument.Create(memoryStream, SpreadsheetDocumentType.Workbook)) { var workbookPart = document.AddWorkbookPart(); workbookPart.Workbook = new Workbook();
var worksheetPart = workbookPart.AddNewPart<WorksheetPart>(); worksheetPart.Worksheet = new Worksheet(new SheetData());
var sheets = workbookPart.Workbook.AppendChild(new Sheets()); sheets.Append(new Sheet() { Id = workbookPart.GetIdOfPart(worksheetPart), SheetId = 1, Name = "Sheet 1" }); }
類別描述:
類別
說明
Workbook
Excel 主要的文件組件的根元素。
Worksheet
Excel 工作表的集合
SheetData
工作表中的資料
Sheets
Sheet 的集合
Sheet
工作表與資料的關聯
概念上的對應大概如下圖:
如果要從 MemoryStream 測試匯出,可以使用 FileStream 存成檔案:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
var memoryStream = new MemoryStream(); using (var document = SpreadsheetDocument.Create(memoryStream, SpreadsheetDocumentType.Workbook)) { // ... // 要從 MemoryStream 匯出,必須先儲存 Workbook,並關閉 SpreadsheetDocument 物件 workbookPart.Workbook.Save(); document.Close();
using (var fileStream = new FileStream("test.xlsx", FileMode.Create)) { memoryStream.WriteTo(fileStream); } }
using System.IO; using DocumentFormat.OpenXml; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Spreadsheet; using Microsoft.AspNetCore.Mvc;
[HttpGet] public FileStreamResult Get() { var memoryStream = new MemoryStream();
using (var document = SpreadsheetDocument.Create(memoryStream, SpreadsheetDocumentType.Workbook)) { var workbookPart = document.AddWorkbookPart(); workbookPart.Workbook = new Workbook();
var worksheetPart = workbookPart.AddNewPart<WorksheetPart>(); worksheetPart.Worksheet = new Worksheet(new SheetData());
var sheets = workbookPart.Workbook.AppendChild(new Sheets());
sheets.Append(new Sheet() { Id = workbookPart.GetIdOfPart(worksheetPart), SheetId = 1, Name = "Sheet 1" });
var sheetData = worksheetPart.Worksheet.GetFirstChild<SheetData>();
var row = new Row(); row.Append( new Cell() { CellValue = new CellValue("No."), DataType = CellValues.String }, new Cell() { CellValue = new CellValue("Name"), DataType = CellValues.String }, new Cell() { CellValue = new CellValue("Links"), DataType = CellValues.String } ); sheetData.AppendChild(row);
for (var i = 0; i < _smapleData.Length; i++) { var data = _smapleData[i]; row = new Row(); row.Append( new Cell() { CellValue = new CellValue((i + 1).ToString()), DataType = CellValues.Number }, new Cell() { CellValue = new CellValue(data[0]), DataType = CellValues.String }, new Cell() { CellValue = new CellValue(data[1]), DataType = CellValues.String } ); sheetData.AppendChild(row); } }