无法在 VS2017 中使用 openxml C# 在特定行之前添加克隆行

Unable to add clone row before a particular row using openxml C# in VS2017

我目前在尝试使用 open xml 克隆和插入一行时遇到问题。

我注意到在我下面的代码中,如果 srcRowIdx 和 refRow 是相同的索引,我将能够克隆具有插入行的行并成功保存 excel sheet .但是,如果 srcRowIdx 和 refRow 不同,excel sheet 将被破坏。任何人都可以启发我为什么会这样?

public Row CopyLine(SpreadsheetDocument excelDoc, string sheetName, int srcRowIdx, int refRow)
            {
                var worksheetPart = GetWorksheetPart(excelDoc, sheetName);
                var sheetData = worksheetPart.Worksheet.Descendants<SheetData>().First();
                var srcRow = GetRow(worksheetPart, srcRowIdx);
                var clonedRow = (Row)srcRow.CloneNode(true);
                var rowRef = GetRow(worksheetPart, refRow);

                //Update all indexes to index+1
                IEnumerable<Row> rows = sheetData.Descendants<Row>().Where(r => r.RowIndex.Value >= refRow);
                foreach (Row row in rows)
                {
                    var clonedRowIndex = Convert.ToUInt32(row.RowIndex.Value + 1);

                    foreach (Cell cell in row.Elements<Cell>())
                    {
                        // Update the references for reserved cells.
                        string cellReference = cell.CellReference.Value;
                        cell.CellReference =
                            new StringValue(cellReference.Replace(row.RowIndex.Value.ToString(), clonedRowIndex.ToString()));
                    }
                    // Update the row index.
                    row.RowIndex = new UInt32Value(clonedRowIndex);
                }

                sheetData.InsertBefore(clonedRow, rowRef);

                worksheetPart.Worksheet.Save();
                return clonedRow;
            }

好的 - 当 src 和 ref 行相等时它起作用的原因是因为在第 4 行:

var clonedRow = (Row)srcRow.CloneNode(true);

您永远不会更改此克隆行的 RowIndex 或任何 CellReferences。所以它总是停留在 src 的索引处。

当src 和ref 相等时,克隆节点的RowIndex 和CellReferences 没问题,之后每行加1。Excel 验证正确。例如,当src和ref为24时,克隆节点CellReferences保持为24,所有24及以上的Rows CellReferences加1,所以sheet是有序的。

但是,以 src 为 24 且 ref 为 27 的情况为例。克隆的行具有 RowIndex 和 CellReferences,其中索引为 24。当您将其插入第 27 个位置并将其后的所有行递增 1 时,那么您的 sheet 行关闭:

  • (从第 23 行开始:)
  • 第 23 行的行索引为 23,单元格的 CellReferences 为 23
  • 第 24 行的行索引为 24,单元格的 CellReferences 为 24
  • 第 25 行的行索引为 25,单元格的 CellReferences 为 25
  • 第 26 行的行索引为 26,单元格的 CellReferences 为 26
  • 第 27 行的行索引为 24,单元格的 CellReferences 为 24
  • 第 28 行的行索引为 28,单元格的 CellReferences 为 28

(以此类推)

当 Excel 打开并验证时,它会在第 27 行阻塞,如果您愿意,它会为您移除。

要解决此问题,您需要将 clonedRows RowIndex 和 CellReferences 更新为目标行号。所以你真的很亲密。