Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NPOI Insert/append value to .xls file

I have problem with append data to existing excel file.

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.

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)

Thanks for help.

like image 437
Przemon Avatar asked Dec 17 '25 12:12

Przemon


1 Answers

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.

like image 84
DevMJ Avatar answered Dec 19 '25 01:12

DevMJ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!