I need to delete certain rows from an excel file. The excel file is a template and may have extra rows, which have to be deleted for the final output. However deletion of the cells corrupts the file. The code is as simple as follows
Worksheet worksheet = worksheetPart.Worksheet;
SheetData sheetData = worksheet.GetFirstChild<SheetData>();
foreach (var row in sheetData.Elements<Row>().
Where(r => r.RowIndex.Value >= rowIndex && r.RowIndex.Value < rowIndex + count).ToList())
{
row.Remove();
}
Alternatively, I tried setting the existing cells to blank values.
Worksheet worksheet = worksheetPart.Worksheet;
SheetData sheetData = worksheet.GetFirstChild<SheetData>();
foreach (var row in sheetData.Elements<Row>().
Where(r => r.RowIndex.Value >= rowIndex && r.RowIndex.Value < rowIndex + count).ToList())
{
IEnumerable<Cell> cells = row.Elements<Cell>().ToList();
if (cells != null)
{
foreach (Cell cell in cells)
{
if (cell.CellValue != null && !String.IsNullOrEmpty(cell.CellValue.Text))
{
cell.DataType = new EnumValue<CellValues>(CellValues.String);
cell.CellValue = new CellValue("");
}
}
}
}
My file always gets corrupted.
The issue was that the final streams to save the worksheet/workbooks, had a mismatch in the sizes.