2 years ago

#77046

test-img

William King

Overwrite an existing Cell in Excel with OpenXML in C#

I am beginning to use OpenXML to update existing Excel file using .NET Core 5 C#.

I have pieced the following code below from examples from the internal and it write to the Excel sheet but I get the following errors when opening the Excel file after running the program.

private static void WriteToExcel(string fileName)
{
    using (SpreadsheetDocument xl = SpreadsheetDocument.Open(fileName, true))
    {
        Sheet sheet = xl.WorkbookPart.Workbook.Sheets.GetFirstChild<Sheet>();
        Worksheet worksheet = (xl.WorkbookPart.GetPartById(sheet.Id.Value) as WorksheetPart).Worksheet;
        IEnumerable<Row> rows = worksheet.GetFirstChild<SheetData>().Descendants<Row>();
        foreach (Row row in rows)
        {
            foreach (Cell cell in row.Descendants<Cell>())
            {
                if (cell.CellReference == "A3")
                {
                    string currentCellValue = xl.WorkbookPart.SharedStringTablePart.SharedStringTable.ChildElements.GetItem(int.Parse(cell.CellValue.InnerText)).InnerText;
                    currentCellValue += "    WRK    ";
                    cell.CellValue = new DocumentFormat.OpenXml.Spreadsheet.CellValue(currentCellValue);
                    cell.DataType = new EnumValue<CellValues>(CellValues.SharedString);
                }
            }
        }
        worksheet.Save();
    }
}
  • Error 1:

We found a problem with some content in -filename-. Do you want us to try to recover as much as we can? If you trust the source of the workbook, click Yes.

I click yes and get this next error.

  • Error 2:

-filename- is locked for editing by 'another user'. Open
'Read-Only' or click 'Notify' to open read-only and receive
notification when the document is no longer in use.

I open in Read-only and can see the " WRK " I added. But I can not save the document because it is in use and readonly.

Any help would be appreciated.

c#

excel

openxml

0 Answers

Your Answer

Accepted video resources