gpt4 book ai didi

.net - 使用 NPOI 更新 excel 文件中的现有单元格值

转载 作者:行者123 更新时间:2023-12-05 00:38:11 30 4
gpt4 key购买 nike

我创建了一个 excel 文件并在 (0,0) [row,cell] 中插入了一个新值作为 您好 .
第二次我打开同一个 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()); 并且该值打印在控制台中。但是当写入工作簿时,文件会损坏。引导我伸出援手。

最佳答案

我在第二部分使用语句中犯了一个错误..

之前:

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

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

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

关于.net - 使用 NPOI 更新 excel 文件中的现有单元格值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37563973/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com