Search code examples
c#.netexcelnpoi

C# program using NPOI to edit cell values of excel(.xls) not working


I wrote the below program to edit the cell value of a excel file(.xls) using NPOI , program is running without errors or exception but the value is not getting updated

 using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Text;
 using System.Threading.Tasks;
 using System.IO;
 using System.Web;
 using NPOI.XSSF.UserModel;
 using NPOI.XSSF.Model;
 using NPOI.HSSF.UserModel;
 using NPOI.HSSF.Model;
 using NPOI.SS.UserModel;
 using NPOI.SS.Util;
 namespace Project37
 {
    class Class1
    {
        public static void Main()
        {
            string pathSource = @"C:\Users\mvmurthy\Desktop\abcd.xls";
            FileStream fs = new FileStream(pathSource, FileMode.Open, FileAccess.ReadWrite); 
            HSSFWorkbook templateWorkbook = new HSSFWorkbook(fs, true);
            HSSFSheet sheet = (HSSFSheet)templateWorkbook.GetSheet("Contents");
            HSSFRow dataRow = (HSSFRow)sheet.GetRow(4);
            dataRow.Cells[2].SetCellValue("foo");
            MemoryStream ms = new MemoryStream();
            templateWorkbook.Write(ms);
            ms.Close();
        }     
    }
}

Solution

  • You have to use FileStream instead of MemoryStream to save your modified file, otherwise you're not actually saving changes you've made to the disk.

    Also note it's better to surround disposable objects like FileStream into using statement to be sure this object will be automatically disposed when it is out of scope.

    So your code could look like:

    string pathSource = @"C:\Users\mvmurthy\Desktop\abcd.xls";
    HSSFWorkbook templateWorkbook;
    HSSFSheet sheet;
    HSSFRow dataRow;
    
    using (var fs = new FileStream(pathSource, FileMode.Open, FileAccess.ReadWrite))
    {
        templateWorkbook = new HSSFWorkbook(fs, true);
        sheet = (HSSFSheet)templateWorkbook.GetSheet("Contents");
        dataRow = (HSSFRow)sheet.GetRow(4);
        dataRow.Cells[0].SetCellValue("foo");
    }
    
    using (var fs = new FileStream(pathSource, FileMode.Open, FileAccess.ReadWrite))
    {
        templateWorkbook.Write(fs);
    }