NPOI乱七八糟的xlsx文件

时间:2013-06-23 22:23:47

标签: c# xlsx npoi

我有以下代码写入现有的XLSX文件

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

使用XLS文件,效果很好。

请帮忙。

此致,Rinaldo

1 个答案:

答案 0 :(得分:0)

我认为错误符合

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

您必须使用正确的Excel文件类型

对工作表对象进行类型转换

尝试

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]);
   }