0

I've tried creating a new Excel file with NPOI and it works OK, reading (only) an Excel file is also OK. However now I want to open an existing Excel file and append some rows on it, it's crashed right at the code line of the NPOI.HSSF.UserModel.HSSFWorkbook constructor. Here is the code:

using(FileStream fs = new FileStream(myFile, FileMode.Append)){
    HSSFWorkbook wb = new HSSFWorkbook(fs); //<-- It is crashed right at here
    ....
}

There is no exception detail, it just shows a window saying that the app is crashed and give 3 options to choose, the middle one is to close the application:
snapshot
That's why I can't understand and feel hard to solve it.

If I change the FileMode to FileMode.Open, the constructor can work well, but that's just for reading. I think there is some thing related to FileAccess policy and tried this:

using(FileStream fs = new FileStream(myFile, FileMode.Append, FileAccess.ReadWrite)){//<-- However it is crashed right at here
    HSSFWorkbook wb = new HSSFWorkbook(fs); 
    ....
}

I've tried a workaround by opening (read only) the existing Excel file, copy 1 sheet of it and add this sheet to a new HSSFWorkbook and write (write only) to a new file stream, however there is no way to do that, because the HSSFWorkbook has no collection of Worksheet and there is also no Add method, the new sheet is just created by CreateSheet() method. It's so annoying.

Could you please help me with this? I'm trying NPOI first, then I'll try EPPlus.
Your help would be highly appreciated.
Thanks.

King King
  • 61,710
  • 16
  • 105
  • 130
  • What are NPOI and EPPlus? – C.B. Apr 21 '13 at 12:35
  • 1
    NPOI is an open source library which is very well-known, it supports handling with *.xls files only. While EPPlus is another open source library which is also very well-known but it supports only *.xlsx files. Using both of these libraries to handle with both *.xls and *.xlsx. You don't need Office installed and I've heard that these lib have a better performance against Open SDK and Office Automation, especially I like EPPlus. The writing speed is faster. You should search for more info, they are both recommended to use for your Excel-related projects, especially good for Web applications. – King King Apr 21 '13 at 13:21

1 Answers1

0

What's your file format? xls or xlsx? If xlsx, you can try NPOI 2.0 now. xlsx is supported. Here is the download link: https://npoi.codeplex.com/releases/view/112932

Tony Qu
  • 676
  • 8
  • 14