Search code examples
.netexcelapachec#-3.0npoi

Update the existing cell value in an excel file using NPOI


I created an excel file and inserted a new value in (0,0) [row,cell] as Hello. Second time I opened the same excel file, same sheet and updated the same (0,0) cell with an another string value.

The code is running successfully without any errors but the file is corrupted and not getting opened.

CODE

namespace PractiseProject
{
    public static class ExcelNPOI
    {
        static IWorkbook workbook;
        static ISheet sheet;
        static IRow row;
        static ICell cell;
        static string file = "C:/Users/MSTEMP/Documents/Files/Test.xlsx";
        static string sheetName = "Testcase";

        public static void createExcel()
        {
            string firstValue = "Hello";
            if (!File.Exists(file))
            {
                using (FileStream str = new FileStream(file, FileMode.Create, FileAccess.Write))
                {
                    workbook = new XSSFWorkbook();
                    sheet = workbook.CreateSheet(sheetName);
                    row = sheet.CreateRow(0);
                    cell = row.CreateCell(0);
                    cell.SetCellValue(firstValue);
                    workbook.Write(str);
                    str.Close();
                }
            }
            else
            {
                using (FileStream rstr = new FileStream(file, FileMode.Open, FileAccess.Read))
                {
                    workbook = new XSSFWorkbook(rstr);
                    sheet = workbook.GetSheet(sheetName);

                    using (FileStream wstr = new FileStream(file, FileMode.Open, FileAccess.ReadWrite))
                    {
                        string secondValue = "changes";

                        row = sheet.GetRow(0);
                        cell = row.GetCell(0);
                        cell.SetCellValue(secondValue);
                        Debug.Print(cell.ToString());
                        workbook.Write(wstr);
                        wstr.Close();
                    }
                    rstr.Close();
                }
            }
        }
    }
}

In Debug mode, after the second value is set cell.SetCellValue(secondValue); I could view the value through Debug.Print(cell.ToString()); and the value is printed in the console. But when writing to the workbook the file gets corrupted. Guide me through reach out.


Solution

  • I made a mistake in else part second using statement..

    Before:

    using (FileStream wstr = new FileStream(file, FileMode.Open, FileAccess.ReadWrite))
    

    Now:

     using (FileStream wstr = new FileStream(file, FileMode.Create, FileAccess.Write))
    

    I changed the FileMode and FileAccess type and now it is working fine.