使用Open XML SDK 2.5在现有的Excel中添加数据

3

我尝试读取现有的Excel文件并复制到另一个路径,然后尝试向我克隆的文件插入数据。但是,我无法插入数据。我不知道我的错误在哪里。但是这里是我的代码。

错误出现在这一行sheetData.InsertAt<Row>(row,++rowIndex);。请帮帮我。

Package spreadsheetPackage = Package.Open(destinationFile, FileMode.Open, FileAccess.ReadWrite);

                using (var document = SpreadsheetDocument.Open(spreadsheetPackage))
                {
                    foreach (System.Data.DataTable table in ds.Tables)
                    {

var workbookPart = document.WorkbookPart;
                            var workbook = workbookPart.Workbook;

                            var sheet = workbookPart.Workbook.Descendants<Sheet>().FirstOrDefault();
                            Worksheet ws = ((WorksheetPart)(workbookPart.GetPartById(sheet.Id))).Worksheet;


                            SheetData sheetData = ws.GetFirstChild<SheetData>();


                            //Sheet sheet = sheets.FirstOrDefault();

                            if(sheet==null)
                                throw new Exception("No sheed found in the template file. Please add the sheet");

                            int rowIndex = 10, colIndex = 0;
                            bool flag = false;

                            var worksheetPart = (WorksheetPart)workbookPart.GetPartById(sheet.Id);
                            var sharedStringPart = workbookPart.SharedStringTablePart;
                            var values = sharedStringPart.SharedStringTable.Elements<SharedStringItem>().ToArray();
                            var rows = worksheetPart.Worksheet.Descendants<Row>();

                            List<String> columns = new List<string>();
                            foreach (System.Data.DataColumn column in table.Columns)
                            {
                                columns.Add(column.ColumnName);
                            }

                            foreach (System.Data.DataRow dsrow in table.Rows)
                            {
                                Row row = new Row();
                                foreach (String col in columns)
                                {
                                    DocumentFormat.OpenXml.Spreadsheet.Cell cell = new Cell();
                                    cell.DataType = DocumentFormat.OpenXml.Spreadsheet.CellValues.String;
                                    cell.CellValue = new DocumentFormat.OpenXml.Spreadsheet.CellValue(dsrow[col].ToString());
                                    row.AppendChild<Cell>(cell);
                                }

                                sheetData.InsertAt<Row>(row,++rowIndex);
                            }

}

请参考以下网址:http://stackoverflow.com/questions/6072456/using-openxml-to-insert-a-datatable-into-excel - BgRva
1个回答

2
在添加行之前,你应该将行索引指定给实例...
row.RowIndex = (UInt32)rowIndex++;

我做了这个++rowIndex; row.RowIndex = (UInt32)rowIndex; sheetData.InsertAt<Row>(row, rowIndex-1); - Dilip

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接