c# - NPOI 将值插入/附加到 .xls 文件

标签 c# excel windows npoi

我在将数据附加到现有 Excel 文件时遇到问题。

代码如下:

HSSFWorkbook hssfwb;
FileStream file1 = new FileStream(pathDoXls, FileMode.Open, FileAccess.Read);
hssfwb = new HSSFWorkbook(file1);

ISheet sheet = hssfwb.GetSheet("Zawodnicy");
int ostatniWiersz = sheet.LastRowNum;
textBox14.Text = (ostatniWiersz+1).ToString();
Console.WriteLine(ostatniWiersz);

ICell cell = sheet.CreateRow(ostatniWiersz+1).CreateCell(0);
cell.SetCellValue(textBox14.Text);

ICell cell1 = sheet.CreateRow(ostatniWiersz + 1).CreateCell(1);
cell1.SetCellValue(textBox2.Text);

//sheet.CreateRow(ostatniWiersz + 1).CreateCell(1).SetCellValue(textBox2.Text);
//sheet.CreateRow(ostatniWiersz + 1).CreateCell(2).SetCellValue(textBox3.Text);

FileStream file = new FileStream(pathDoXls, FileMode.Create);
hssfwb.Write(file);
file.Close();

理论上这部分代码:

ICell cell = sheet.CreateRow(ostatniWiersz+1).CreateCell(0);
cell.SetCellValue(textBox14.Text);

ICell cell1 = sheet.CreateRow(ostatniWiersz + 1).CreateCell(1);
cell1.SetCellValue(textBox2.Text);

应该在最后一行位置创建单元格,我的意思是:

ostatniWiersz=10

因此第 11 行和单元格 0 中应该是 textBox14 内容 第 11 行单元格 1 应该是 textBox2 内容。

但是当我编译此代码时,我仅在第 11 行单元格 1 中具有值。理论上,值应该插入到两个字段中(我的意思是单元格 0 和 1)

感谢您的帮助。

最佳答案

您正在覆盖同一行,这就是下面代码的效果丢失的原因

ICell cell = sheet.CreateRow(ostatniWiersz+1).CreateCell(0);
cell.SetCellValue(textBox14.Text);

尝试使用下面的代码。

    HSSFWorkbook hssfwb;
    FileStream file1 = new FileStream(pathDoXls, FileMode.Open, FileAccess.Read);
    hssfwb = new HSSFWorkbook(file1);

    ISheet sheet = hssfwb.GetSheet("Zawodnicy");
    int ostatniWiersz = sheet.LastRowNum;
    textBox14.Text = (ostatniWiersz + 1).ToString();
    Console.WriteLine(ostatniWiersz);

    IRow worksheetRow = sheet.CreateRow(ostatniWiersz + 1);

    ICell cell = worksheetRow.CreateCell(0);
    cell.SetCellValue(textBox14.Text);

    ICell cell1 = worksheetRow.CreateCell(1);
    cell1.SetCellValue(textBox2.Text);

    //sheet.CreateRow(ostatniWiersz + 1).CreateCell(1).SetCellValue(textBox2.Text);
    //sheet.CreateRow(ostatniWiersz + 1).CreateCell(2).SetCellValue(textBox3.Text);

    FileStream file = new FileStream(pathDoXls, FileMode.Create);
    hssfwb.Write(file);
    file.Close();

希望能解决您的问题。

关于c# - NPOI 将值插入/附加到 .xls 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43725258/

相关文章:

c# - For循环将图像添加到图像列表

c# - Button Submit 先调用Onload!

windows - Windows下用--ssl参数运行mongo 3.2.4

python - 根据单元格值定位行

windows - 将命令的结果保存在变量中,Windows 批处理

windows - 使用 at 访问共享网络

c# - 在 RDotNet.dll 中发生类型为 'System.StackOverflowException' 的未处理异常以在 Web 应用程序中加载 R 库

c# - 如何在 .NET Core 6 中为 HttpClientFactory 设置不同的配置

Excel VBA 函数根据范围内的单元格背景颜色返回 True 或 False

透视数据所需的 Excel Vlookup 公式