Open XML:如何使用c#

时间:2016-12-21 14:55:22

标签: c# excel openxml-sdk

我使用开放XML在现有Excel文件中插入/附加新工作表,但我无法添加行和单元格值。以下是我的代码:

  using (var workbook = SpreadsheetDocument.Open(excelFilePath, true))
            {
                var workbookPart = workbook.WorkbookPart;
                var wb = workbookPart.Workbook;
                int rowIndex = 0;
                // Add a blank WorksheetPart.
                WorksheetPart newWorksheetPart = workbook.WorkbookPart.AddNewPart<WorksheetPart>();
                newWorksheetPart.Worksheet = new Worksheet(new SheetData());
                Sheets sheets = workbook.WorkbookPart.Workbook.GetFirstChild<Sheets>();
                string relationshipId = workbook.WorkbookPart.GetIdOfPart(newWorksheetPart);

                // Get a unique ID for the new worksheet.
                uint sheetId = 1;
                if (sheets.Elements<Sheet>().Count() > 0)
                {
                    sheetId = sheets.Elements<Sheet>().Select(s => s.SheetId.Value).Max() + 1;
                }

                // Give the new worksheet a name.
                string sheetName = "Data";

                // Append the new worksheet and associate it with the workbook.
                Sheet dataSheet = new Sheet() { Id = relationshipId, SheetId = sheetId, Name = sheetName };
                sheets.Append(sheet);
                workbookPart.Workbook.Save();
                var sharedStringPart = workbookPart.SharedStringTablePart;
                var values = sharedStringPart.SharedStringTable.Elements<SharedStringItem>().ToArray();
                Row headerRow = new Row();
                Cell cell = new Cell();
                cell.DataType = CellValues.String;
                cell.CellValue = new CellValue("EmpId");
                headerRow.AppendChild<Cell>(cell);
                cell = new Cell();
                cell.DataType = CellValues.String;
                cell.CellValue = new CellValue("Name");
                headerRow.AppendChild<Cell>(cell);

                headerRow.AppendChild<Cell>(cell);
                dataSheet.InsertAt<Row>(headerRow, rowIndex++);
                workbookPart.Workbook.Save();
            }
        }

这是一个例外:

  

非复合元素没有子元素。

0 个答案:

没有答案