Search code examples
c#excelnpoi

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)

Solution

  • 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 :-))