【问题标题】:C# program using NPOI to edit cell values of excel(.xls) not working [duplicate]使用 NPOI 编辑 excel(.xls)的单元格值的 C# 程序不起作用 [重复]
【发布时间】:2016-08-19 16:58:59
【问题描述】:

我编写了以下程序来使用 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();
        }     
    }
}

【问题讨论】:

    标签: c# .net excel npoi


    【解决方案1】:

    您必须使用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);
    }
    

    【讨论】:

    • 非常感谢!安迪·科涅耶夫
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-19
    • 1970-01-01
    • 2018-03-25
    • 1970-01-01
    相关资源
    最近更新 更多