Search code examples
c#npoi

Updating a cell value breaks row style. NPOI, C#


Good evening, recently i was trying to update cell's value in .xls file, using NPOI library(C#), but, when i do that with cell.SetCellValue("anyvalue");,

I am able to see the changes only in some cells. Other cell are just empty.

Tried to save cell's style and re-write it using cell.CellStyle, but still the same.

Generally speaking, i get only half of the values that have to be filled in places.

Using that code, where nameAndValues[0] contains cell name, and nameAndValues[1] contains its value.

using (FileStream rstr = new FileStream(currentPath + $"/{excelName}", FileMode.Open, FileAccess.Read))
                {
                    var workbook = new HSSFWorkbook(rstr);
                    var sheet = workbook.GetSheetAt(0);
                    using (FileStream wstr = new FileStream(currentPath + $"/{excelName}", FileMode.Open, FileAccess.Write))
                    {
                        for (int i = 0; i < values.Count; i++)
                        {
                            var cr = new CellReference(namesAndValue[i, 0]);
                            var row = sheet.CreateRow(cr.Row);
                            var cell = row.CreateCell(cr.Col);
                            cell.SetCellValue(namesAndValue[i, 1]);

                        }
                        workbook.Write(wstr);
                        wstr.Close();
                    }
                    rstr.Close();
                }

Solution

  • When you call sheet.CreateRow(0), the first row of the sheet will be wiped out and an empty row will be inserted with no style. The same goes with row.CreateCell().

    So you are calling CreateRow over and over again, making only the last value of the row survive.

    I think this might be the problem.