将Open XML文档保存为Excel文件可以通过以下步骤实现:
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Create("output.xlsx", SpreadsheetDocumentType.Workbook))
{
// 创建Workbook部分
spreadsheetDocument.AddWorkbookPart();
spreadsheetDocument.WorkbookPart.Workbook = new Workbook();
// 创建Worksheet部分
spreadsheetDocument.WorkbookPart.AddNewPart<WorksheetPart>();
spreadsheetDocument.WorkbookPart.WorksheetParts.First().Worksheet = new Worksheet(new SheetData());
// 创建Sheet部分
spreadsheetDocument.WorkbookPart.Workbook.AppendChild(new Sheets());
spreadsheetDocument.WorkbookPart.Workbook.GetFirstChild<Sheets>().AppendChild(new Sheet()
{
Id = spreadsheetDocument.WorkbookPart.GetIdOfPart(spreadsheetDocument.WorkbookPart.WorksheetParts.First()),
SheetId = 1,
Name = "Sheet1"
});
// 保存并关闭文档
spreadsheetDocument.WorkbookPart.Workbook.Save();
spreadsheetDocument.Close();
}
using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open("input.xlsx", true))
{
// 获取第一个Worksheet部分
WorksheetPart worksheetPart = spreadsheetDocument.WorkbookPart.WorksheetParts.First();
Worksheet worksheet = worksheetPart.Worksheet;
// 在指定单元格写入数据
Cell cell = InsertCellInWorksheet("A", 1, worksheetPart);
cell.CellValue = new CellValue("Hello World!");
cell.DataType = new EnumValue<CellValues>(CellValues.String);
// 保存并关闭文档
worksheet.Save();
spreadsheetDocument.Close();
}
以上代码示例使用了Open XML SDK来操作Excel文件。在创建新的Excel文件时,需要创建Workbook、Worksheet和Sheet等部分,并将它们逐级添加到文档中。在打开现有的Excel文件时,可以通过WorksheetPart来获取和修改工作表的内容。
请注意,以上示例仅涵盖了基本的保存和打开Excel文件的操作,实际应用中可能需要根据具体需求进行更复杂的操作,如添加样式、合并单元格、设置公式等。
腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云