Can't edit the existing Excel file with NPOI? - c#

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

Related

NPOI corrupting xlsm workbook

I am required to write some data into an macro enabled workbook which was developed in 1998, i am using NPOI dotnet core library for this task. I am able to write the values into the excel correctly, however i am seeing that alignment and formatting of the sheets is lost. Screenshots below:
First one shows the file after open the file using NPOI and downloading the same, and second shows the file when it is locally opened.
below is the code i am using
public XSSFWorkbook OpenExcelFile(string filePath, string tempSavePath)
{
using (var stream = new FileStream(tempSavePath, FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
var temphssfwb = new XSSFWorkbook(OPCPackage.Open(filePath));
temphssfwb.Write(stream);
}
XSSFWorkbook hssfwb;
hssfwb = new XSSFWorkbook(OPCPackage.Open(tempSavePath));
hssfwb.CreateSheet("casevalidationsheet");
return hssfwb;
}
Can someone please help me understand why NPOI is ruining the alignment of my excel workbook?

Npoi xls file save corrupts excel file

So I am able to open and dig through an xls (Excel 97-2003) file. However, the problem is when I try to save it. After I save it, and it succeeds, I then go and manually open the Excel file and get an error saying that it cannot open the Excel file and that it is corrupt. This happens regardless of whether I make any changes or not.
I am still able to, within the program, open the excel file and read through the data.
I am using NPOI 2.2.1 and 2.3.0 (which I installed via Nuget). Both versions have the same results.
string excelLocation = settings.GetExcelDirectory() + week.ExcelLocation;
HSSFWorkbook wbXLS;
// Try to open and read existing workbook
using (FileStream stream = new FileStream(excelLocation, FileMode.Open, FileAccess.Read))
{
wbXLS = new HSSFWorkbook(stream);
}
ISheet sheet = wbXLS.GetSheet("Schedule");
using (FileStream stream = new FileStream(excelLocation, FileMode.Create, FileAccess.Write))
{
wbXLS.Write(stream);
}
Do you have multi-line cell contents (with a line break)?
I just came across such a problem with my column headers in row 0.
Excel encodes a line break by replacing it with _x000a_ (i.e. line1_x000a_line2), NPOI doesn't do that.
Tried with nuget 2.3.0 and xlsx file, but might also be helpful in your case.
I worked around (and verified the cause) by replacing line feeds before saving:
// Encode LineFeeds in column headers (row 0)
IRow rowColHeaders = sheet.GetRow(0);
foreach (ICell cell in rowColHeaders.Cells)
{
string content = cell.StringCellValue;
if (content.Contains("\n"))
cell.SetCellValue(content.Replace("\n", "_x000a_"));
}
try something like
FileStream sw = File.Create(excelLocation);
wbXLS.Write(sw);
sw.Close();

NPOI ArgumentOutOfRangeException on WorkbookFactory.Create

I have been using NPOI to read Excel files, and I now need to write out files. I am trying to use the WorkbookFactory, which doesn't show up in a lot of examples online (doesn't appear in the NPOI examples on CodePlex either). Here is the code:
this.FileStream = new FileStream(
this.FilePath,
FileMode.OpenOrCreate,
FileAccess.ReadWrite);
this.Workbook = WorkbookFactory.Create(
this.FileStream);
When it gets to the second statement, I get an ArgumentOutOfRangeException with the following message: "Non-negative number required.\r\nParameter name: value".
Next few lines in the call stack:
at System.IO.FileStream.set_Position(Int64 value)
at NPOI.Util.PushbackStream.set_Position(Int64 value)
at NPOI.POIXMLDocument.HasOOXMLHeader(Stream inp)
at NPOI.SS.UserModel.WorkbookFactory.Create(Stream inputStream)
The WorkbookFactory (link to POI documentation) reads existing file data from an input stream, and determines on the fly whether to create an HSSFWorkbook or an XSSFWorkbook (i.e. whether you are working with XLS or XLSX-like files).
From your code, it seems you are trying to create a new file using this class. That is not something the WorkbookFactory can help you with. To write files, use the following pattern:
var workbook = new XSSFWorkbook();
...
using (var fileData = new FileStream(#"path\filename.xlsx", FileMode.Create))
{
workbook.Write(fileData);
}
(In other words, WorkbookFactory is a class factory, not a file factory :-))

C# port of Apache POI corrupts embedded OLE objects in .xlsx

I'm working on a program that processes .xlsx workbooks and reformats them to match a style guide. And on the first sheet of these documents there is an embedded OLE object (a word document) that details aspects of the files.
Whenever I save back my workbook the object gets corrupted, even if skip the first sheet when I execute my processing.
My load and save back code is as follows:
FileStream fStream = new FileStream(file, FileMode.Open, FileAccess.Read);
IWorkbook wb = new XSSFWorkbook(fStream);
fStream.Close();
//do stuff
fStream = new FileStream(file, FileMode.Create, FileAccess.Write);
wb.Write(fStream);
fStream.Close();
The documentation falls short on answering my questions, and previously asked SO questions have remained unanswered so I'm guessing this is either quite a complicated problem or a ridiculously stupid mistake either way I hope you guys can be of assistance.

.NET C# - Importing Excel File - Sheet Name!

I'm using the NPOI Library to import some data from an excel sheet to my database.
One early issue I'm curious about, is typically, to begin, you would have something like this:
snippet
using (FileStream fs = File.Open(filename, FileMode.Open, FileAccess.Read))
{
HSSFWorkbook templateWorkbook = new HSSFWorkbook(fs);
HSSFSheet sheet = templateWorkbook.GetSheet("Sales");
My query is, what happens when the name of the worksheet is different each time, e.g. I plan to import sales data, and the sheets within the workbooks I receive from suppliers are titled by date.
Is there any way that you can specify GetSheet(); to just get the first sheet in the workbook?
Any pointers would be much appreciated,
thanks guys :)
Without trying it out I'd assume that you're looking for getSheetAt.
So it would be:
HSSFSheet sheet = templateWorkbook.GetSheetAt(0);

Categories

Resources