This question already has an answer here:
Trying to edit cell value of existing Excel file using NPOI
                                
                                    (1个答案)
                                
                        
                                3年前关闭。
            
                    
我写了下面的程序来使用NPOI编辑excel文件(.xls)的单元格值,程序正在运行,没有错误或异常,但该值没有得到更新

 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();
        }
    }
}

最佳答案

您必须使用FileStream而不是MemoryStream来保存修改后的文件,否则实际上并不会保存对磁盘所做的更改。

另请注意,最好将FileStream之类的一次性对象包围在using语句中,以确保在超出范围时该对象将自动处置。

因此您的代码可能如下所示:

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);
}

09-28 05:27