首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >用C#程序编辑excel(.xls)不工作的单元格值

用C#程序编辑excel(.xls)不工作的单元格值
EN

Stack Overflow用户
提问于 2016-08-19 08:25:05
回答 1查看 4.8K关注 0票数 1

我编写了下面的程序来编辑excel文件(.xls)的单元格值,程序运行时没有错误或异常,但是该值没有更新。

代码语言:javascript
运行
复制
 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();
        }     
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-08-19 08:46:50

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

还请注意,最好将FileStream这样的一次性对象包围到using语句中,以确保该对象在超出作用域时会自动释放。

因此,您的代码看起来可能如下:

代码语言:javascript
运行
复制
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);
}
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39034401

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档