Can't edit the existing Excel file with NPOI?
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.
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
链接地址: http://www.djcxy.com/p/35758.html