這是一個從下面的鏈接取得的例子,易於理解和使用。這將創建該文件。然後創建工作表和後來的名稱分配給工作表,就像這樣:
sheet.Name="ohyessheet";
不要忘了「WindowsBase」添加到參考項目。此外,使用命名空間添加此:
using DocumentFormat;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
這是函數來創建Excel文件,但您可能只需要工作表信息。無論如何,下面是創建文件並創建工作表的完整示例。
How to: Create a spreadsheet document by providing a file name (Open XML SDK)
CreateSpreadsheetWorkbook(@".\MyExcelFile.xlsx");
,並使用CreateSpreadsheetWorkbook做真正的工作:
public static void CreateSpreadsheetWorkbook(string filepath)
{
// Create a spreadsheet document by supplying the filepath.
// By default, AutoSave = true, Editable = true, and Type = xlsx.
SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.
Create(filepath, SpreadsheetDocumentType.Workbook);
// Add a WorkbookPart to the document.
WorkbookPart workbookpart = spreadsheetDocument.AddWorkbookPart();
workbookpart.Workbook = new Workbook();
// Add a WorksheetPart to the WorkbookPart.
WorksheetPart worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
worksheetPart.Worksheet = new Worksheet(new SheetData());
// Add Sheets to the Workbook.
Sheets sheets = spreadsheetDocument.WorkbookPart.Workbook.
AppendChild<Sheets>(new Sheets());
// Append a new worksheet and associate it with the workbook.
Sheet sheet = new Sheet()
{
Id = spreadsheetDocument.WorkbookPart.
GetIdOfPart(worksheetPart),
SheetId = 1,
Name = "mySheetNameISHere!"
};
sheets.Append(sheet);
workbookpart.Workbook.Save();
// Close the document.
spreadsheetDocument.Close();
}