Rien Rinaldini
Rien Rinaldini

Reputation: 55

NPOI makes a mess of xlsx files

I have the following code to write to an existing XLSX file

FileStream file = new FileStream(bestand, FileMode.Open, FileAccess.ReadWrite);
string ext = Path.GetExtension(bestand).ToLower();

if (ext == ".xls")
{
    wb = new HSSFWorkbook(file);
}
else if (ext == ".xlsx")
    wb = new XSSFWorkbook(file);

ISheet ws = wb.GetSheet(Maanden[maand-1]);

ws.GetRow(colum).GetCell(rij++).SetCellValue(huidigedatum);
ws.GetRow(colum).GetCell(rij++).SetCellValue(Datarow["Factuurnummer"].ToString());
ws.GetRow(colum).GetCell(rij++).SetCellValue(Datarow["Omschrijving"].ToString());
ws.GetRow(colum++).GetCell(tbBank-1).SetCellValue((double)totaal);

WriteToFile(bestand);
private void WriteToFile(string bestand)
{
    //Write the stream data of workbook to the root directory
    FileStream file = new FileStream(bestand, FileMode.Create);
    wb.Write(file);
    pBar.PerformStep();
    file.Close();
}

With an XLS file it works great.

Please help.

Regards, Rinaldo

Upvotes: 1

Views: 1781

Answers (1)

kumar chandraketu
kumar chandraketu

Reputation: 2370

What I think is error is in line

ISheet ws = wb.GetSheet(Maanden[maand-1]);

you'll have to typecaste the worksheet object with correct excel file type

try

ISheet ws;
   if (ext == ".xls")
   {
    wb = new HSSFWorkbook(file);
    ws = (HSSFSheet)wb.GetSheet(Maanden[maand-1]);
   }
   else if (ext == ".xlsx")
   { 
      wb = new XSSFWorkbook(file);
      ws = (XSSFSheet)wb.GetSheet(Maanden[maand-1]);
   }

Upvotes: 1

Related Questions