简体   繁体   English

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

[英]NPOI Insert/append value to .xls file

I have problem with append data to existing excel file. 将数据追加到现有的excel文件时出现问题。

Here is the code: 这是代码:

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

Theoretically this part of code : 理论上这部分代码:

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

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

Should create cell in last row position, I mean: 应该在最后一行位置创建单元格,我的意思是:

ostatniWiersz=10

so in row 11 and cell 0 should be textBox14 content in row 11 cell 1 should be textBox2 content. 因此,第11行和单元格0应该是textBox14内容,第11行单元格1应该是textBox2内容。

But when I compile this code I have value only in row 11 cell 1. Theoretically value should be insert at both fields(I mean cell 0 and 1) 但是,当我编译此代码时,我仅在第11行的单元格1中具有值。理论上,应该在两个字段中都插入值(我的意思是单元格0和1)

Thanks for help. 感谢帮助。

You are overwriting same row, thats why effect of below code has lost 您正在覆盖同一行,这就是为什么以下代码的效果已消失的原因

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

Try using below code. 尝试使用以下代码。

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

Hope it will solve your problem. 希望它能解决您的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM