使用 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 的工作表创建。