I am currently having an issue when I try to clone and insert a line using open xml.
I noticed that in my code below, if the srcRowIdx and the refRow is the same index, I would be able to clone the row with the inserted line and save the excel sheet successfully. However, if srcRowIdx and refRow is different, the excel sheet will be corrupted. Anyone able to enlighten me on why this is so?
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;
}