使用 OpenXML 建立一個新的電子表格
此方法將建立一個新的 Excel 電子表格。傳入 fileName
,這是一個完整的檔案路徑名。
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using System;
....
void Create(string fileName)
{
using (SpreadsheetDocument document = SpreadsheetDocument.Create(fileName, SpreadsheetDocumentType.Workbook))
{
var relationshipId = "rId1";
//build Workbook Part
var workbookPart = document.AddWorkbookPart();
var workbook = new Workbook();
var sheets = new Sheets();
var sheet1 = new Sheet() { Name = "First Sheet", SheetId = 1, Id = relationshipId };
sheets.Append(sheet1);
workbook.Append(sheets);
workbookPart.Workbook = workbook;
//build Worksheet Part
var workSheetPart = workbookPart.AddNewPart<WorksheetPart>(relationshipId);
var workSheet = new Worksheet();
workSheet.Append(new SheetData());
workSheetPart.Worksheet = workSheet;
//add document properties
document.PackageProperties.Creator = "Your Name";
document.PackageProperties.Created = DateTime.UtcNow;
}
對於此專案,請確保包含對 DocumentFormat.OpenXml
的引用。它位於安裝 OpenXML 示例中指定的路徑中。
電子表格將使用你的姓名作為作者和第一個名為 First Sheet 的工作表建立。