【问题标题】:Update the existing cell value in an excel file using NPOI使用 NPOI 更新 excel 文件中的现有单元格值
【发布时间】:2016-06-01 08:57:52
【问题描述】:

我创建了一个 excel 文件并在 (0,0) [row,cell] 中插入了一个新值作为 Hello。 我第二次打开同一个 excel 文件、同一张工作表并用另一个字符串值更新了同一个 (0,0) 单元格。

代码运行成功,没有任何错误,但文件已损坏且无法打开。

代码

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

在Debug模式下,设置第二个值后cell.SetCellValue(secondValue);可以通过Debug.Print(cell.ToString());查看值> 并且该值打印在控制台中。但是当写入工作簿时,文件会损坏。指导我伸出援手。

【问题讨论】:

    标签: .net excel apache c#-3.0 npoi


    【解决方案1】:

    我在 else part second using 语句中犯了一个错误..

    之前:

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

    现在:

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

    我更改了 FileMode 和 FileAccess 类型,现在可以正常工作了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-25
      相关资源
      最近更新 更多