我在我的应用程序中使用“documentformat.openxml.spreadsheet.worksheet”。
如果我使用Sheet,我可以为其分配名称,如下所示。
var sheet = new Sheet();
sheet.Name = "XYZ";
如果我使用工作表,我无法指定名称。如何为工作表分配名称?
var worksheet = new Worksheet();
答案 0 :(得分:1)
这是一个从以下链接中获取的示例,易于理解和使用。这会创建文件。然后创建工作表,稍后为工作表指定一个名称,如下所示:
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();
}