12

I currently have this code to open an xlsx file using apache POI

File existingXlsx = new File("/app/app.xlsx");
System.out.println("File Exists: " + existingXlsx.exists());

Workbook workbook = WorkbookFactory.create(existingXlsx);

When I try to execute this, I get the following output

File Exists: true
java.lang.NullPointerException
    at org.apache.poi.xssf.usermodel.XSSFWorkbook.onDocumentRead(XSSFWorkbook.java:270)
    at org.apache.poi.POIXMLDocument.load(POIXMLDocument.java:159)
    at org.apache.poi.xssf.usermodel.XSSFWorkbook.<init>(XSSFWorkbook.java:186)
    at org.apache.poi.ss.usermodel.WorkbookFactory.create(WorkbookFactory.java:91)

The file I am trying to open can be opened in Excel and show the data correctly, what can I do to get POI to read the XLSX file?

Here is the file that breaks;

https://mega.co.nz/#!FJMWjQKI!CzihQgMVpxOQDTXzSnb3UFYSKbx4yFTb03-LI3iLmkE

Edit

I have also tried, this results in the same error;

Workbook workbook = new XSSFWorkbook(new FileInputStream(existingXlsx));

Edit

I found the line it is throwing the exception on;

WorkbookDocument doc = WorkbookDocument.Factory.parse(getPackagePart().getInputStream());
this.workbook = doc.getWorkbook();

Map<String, XSSFSheet> shIdMap = new HashMap<String, XSSFSheet>();
for(POIXMLDocumentPart p : getRelations())
{
    if(p instanceof SharedStringsTable) sharedStringSource = (SharedStringsTable)p;
    else if(p instanceof StylesTable) stylesSource = (StylesTable)p;
    else if(p instanceof ThemesTable) theme = (ThemesTable)p;
    else if(p instanceof CalculationChain) calcChain = (CalculationChain)p;
    else if(p instanceof MapInfo) mapInfo = (MapInfo)p;
    else if (p instanceof XSSFSheet) {
        shIdMap.put(p.getPackageRelationship().getId(), (XSSFSheet)p);
    }
}

stylesSource.setTheme(theme); <== BREAKS HERE

Edit

After some research POI seems to be unable to find the styles.xml and the workbook.xml, I find this strange because a simple reader like TextWrangler which shows the structure of the archive shows me the styles xml.

How do I fix this? Is there a default styles.xml and workbook.xml which I can insert into the archive?

Thizzer
  • 16,153
  • 28
  • 98
  • 139
  • do you have the sources? you can debug it – nachokk Aug 16 '13 at 13:54
  • Do you have read access to the file? Are you also sure it's not a directory? Other than that, I'd go with what @nachokk said and debug. – John Farrelly Aug 16 '13 at 14:00
  • See edit, the line has something to do with stylesSource.setTheme(theme); – Thizzer Aug 16 '13 at 14:01
  • it seems stylesSource is null then – nachokk Aug 16 '13 at 14:03
  • would be better if you could paste more of your code as it is tough to guess what the styleSource.setTheme(theme) does. – rahulserver Aug 16 '13 at 14:04
  • If possible pls share the excel sheet, also show the full stacktrace – Prashant Bhate Aug 16 '13 at 14:16
  • Due to privacy restrictions I can't share the exact xlsx – Thizzer Aug 16 '13 at 14:18
  • you should provide a [SSCCE](http://www.sscce.org) for better sooner help, you can edit the xlsx data that you are parsing.. – nachokk Aug 16 '13 at 14:38
  • Added an attachment (the file that throws the exception) – Thizzer Aug 16 '13 at 14:45
  • 2
    What version of Apache POI are you using? And if it isn't the latest one, have you tried upgrading? – Gagravarr Aug 16 '13 at 15:41
  • I have tried 3.6, 3.7, 3.8 and 3.9, can't seem to get to download the 3.10 beta, all the mirrors are broken – Thizzer Aug 16 '13 at 20:09
  • After some research POI seems to be unable to find the styles.xml and the workbook.xml, I find this strange because a simple reader like TextWrangler which shows the structure of the archive shows me the styles xml. – Thizzer Aug 20 '13 at 06:48
  • I have downloaded your test2.xlsx file, and can open it with no errors using POI 3.8. The exact jar files I used are poi-ooxml-3.8-20120326.jar, poi-3.8-20120326.jar, xbean.jar (from the xmlbeans-2.6.0 library), poi-ooxml-schemas-3.8-20120326.jar, and dom4j-1.6.1.jar. Therefore I don't think the problem is with POI, it is more likely to be something in your set up which is causing the problem? I can send you the links for downloading these exact jar files if it helps? – Wee Shetland Aug 20 '13 at 10:55
  • Works fine with 3.9 too. – Jonathan Drapeau Aug 21 '13 at 18:20
  • Are you trying to open and write more than once the same file? – Jonathan Drapeau Aug 21 '13 at 18:29
  • 1
    I was able to download your xls sheet and read it via POI 3.9. The styles.xml and workbook.xml are automatically retrieved/generated by POI . In my run there was no NullPointerException as stylesSource was correctly initialized in the for loop. I suspect something wrong with your classpath or jars used..Can you create a new very simple xls file, add just 1 value in it in 1 cell and see if you are able to read that with your current settings ? Just want to confirm if you are facing issues will all xls file or just this one .. – Zenil Aug 21 '13 at 22:25
  • @Thizzer, Did you solved the NullPointerException issue? I'm facing the same issue with my JSP web application. I 'm using the latest POI ver 4.1.2. I tried from a simple java appl that reads from xlsx file using POI and it works without issues. It is only with JSP web application, that i get this exception. I configured the same JSP web application in my colleagues machine and it worked in his machine. I'm not sure what is the missing piece in my system. We both are using Tomcat 9.0.31 server. Thank you in advance for your help. Here is my SO link: https://stackoverflow.com/q/60436187/2174455 – Hemant Mar 03 '20 at 06:51

3 Answers3

5

Now I've dowloaded the latest packages:

  • poi-src-3.9-20121203.zip (As source)
  • xmlbeans-2.6.0.zip
    • jsr173_1.0_api.jar
    • resolver.jar
    • xbean.jar
    • xbean_xpath.jar
    • xmlbeans-qname.jar
    • xmlpublic.jar
  • ooxml-schemas-1.1.jar
  • dom4j-1.6.1.jar
  • commons-codec-1.8.jar
  • commons-logging-1.1.3.jar
  • ant.jar (ant 1.7)

And your test2.xlsx were read without problems:

  public static void main(String arg []){
    try {
      //File existingXlsx = new File("/app/app.xlsx");
      File existingXlsx = new File("c:/Java/poi-3.9/test-data/__theproblem/test2.xlsx");
      System.out.println("File Exists: " + existingXlsx.exists());

      Workbook workbook = WorkbookFactory.create(existingXlsx);

    } catch (Exception e) {
      e.printStackTrace();
    }
  }

Are you sure you're using ooxml-schemas-1.1.jar as the POI documentation recommends?

EDIT

Hmm. It's work for me from jar too.

  1. I have downloaded poi-bin-3.9-20121203.tar.gz from http://poi.apache.org/download.html

  2. Made a new project in Eclipse, extracted all the jars from the zip:

    • lib/commons-codec-1.5.jar
    • lib/commons-logging-1.1.jar
    • lib/dom4j-1.6.1.jar
    • lib/junit-3.8.1.jar
    • lib/log4j-1.2.13.jar
    • lib/poi-3.9-20121203.jar
    • lib/poi-examples-3.9-20121203.jar
    • lib/poi-excelant-3.9-20121203.jar
    • lib/poi-ooxml-3.9-20121203.jar
    • lib/poi-ooxml-schemas-3.9-20121203.jar
    • lib/poi-scratchpad-3.9-20121203.jar
    • lib/stax-api-1.0.1.jar
    • lib/xmlbeans-2.3.0.jar
  3. Add the test xlsx:
    • test-data/test2.xlsx
  4. The test Java:
    • src/XlsxReadTest1.java

Source:

    import java.io.File;
    import org.apache.poi.ss.usermodel.Workbook;
    import org.apache.poi.ss.usermodel.WorkbookFactory;

    public class XlsxReadTest1 {
      public static void main(String arg []){
        try {

          File existingXlsx = new File("c:/Java/__Work/apache_POI/poi-3.9-bin/test-data/test2.xlsx");
          System.out.println("File Exists: " + existingXlsx.exists());

          Workbook workbook = WorkbookFactory.create(existingXlsx);

          System.out.println("A1: " + workbook.getSheetAt(0).getRow(0).getCell(0).getStringCellValue());

        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    }
  1. Run. (Tried with jdk1.7.0_07, jdk1.6.0_31)

  2. Result:

    File Exists: true
    A1: Testing Edit
    

"Testing Edit" is the content of the first cell on the first sheet of your file.

I think, You may try this, from scratch.

(Maybe you are using other jars for your project, whom interfere with this jars in the class loader? Class loader is a cunning guy...)

MGM
  • 359
  • 3
  • 10
  • I am using the poi-ooxml-schemas-3.9-20121203.jar which is included in the binary zip, no idea which version of the schemas that is. – Thizzer Aug 21 '13 at 07:06
  • I tried using the ooxml-schemas-1.1.jar but that still results in the NullPointerException – Thizzer Aug 21 '13 at 10:40
  • dom4j, xmlbeans is the latest version? Very interesting, it's woked me for first run. (After a few hours of hunting the required jars - as described above - to compile the POI source... ;)) (It's on my home computer, I will try it with the POI jar at evening, CET.) – MGM Aug 21 '13 at 12:07
  • *(I have edited the Answer, added second phase with the jars.)* – MGM Aug 21 '13 at 20:53
  • I tried you're exact code, and the binary. I am still getting the NullpointerException, what platform are you running on? Can the problem lie somewhere in the fact that I am using OSX? – Thizzer Aug 26 '13 at 09:59
4

I guess you just used the wrong poi package. Try to download the following or you check the newest version from the page.

The following I tested in my Eclipse development:

http://www.apache.org/dyn/closer.cgi/poi/release/bin/poi-bin-3.9-20121203.zip extract it, and include all the jars into your eclipse lib

eclipse structure

I combine user1234's answer and my own approach, both are working on your test2.xlsx

            import java.io.File;
            import java.io.FileInputStream;
            import java.io.FileNotFoundException;
            import java.io.IOException;

            import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
            import org.apache.poi.openxml4j.opc.OPCPackage;
            import org.apache.poi.ss.usermodel.Cell;
            import org.apache.poi.ss.usermodel.Row;
            import org.apache.poi.ss.usermodel.Sheet;
            import org.apache.poi.ss.usermodel.Workbook;
            import org.apache.poi.xssf.extractor.XSSFExcelExtractor;
            import org.apache.poi.xssf.usermodel.XSSFWorkbook;
            import org.apache.xmlbeans.XmlException;


            public class Main {

                /**
                 * @param args
                 */
                public static void main(String[] args) {
                    //      File existingXlsx = new File("app.xlsx");

                    File file = new File("test2.xlsx");
                    FileInputStream fs;
                    try {
                        fs = new FileInputStream(file);

                        OPCPackage xlsx = OPCPackage.open(fs);
                        XSSFExcelExtractor xe = new XSSFExcelExtractor(xlsx);
                        System.out.println(xe.getText());


                    } catch (FileNotFoundException e1) {
                        e1.printStackTrace();
                    } catch (XmlException e) {
                        e.printStackTrace();
                    } catch (OpenXML4JException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    /// -------------- Another approach

                    File existingXlsx = new File("test2.xlsx");
                    System.out.println("File Exists: " + existingXlsx.exists());

                    try {
                        Workbook workbook = new XSSFWorkbook(new FileInputStream(
                            existingXlsx));

                        Sheet worksheet = workbook.getSheet("Filter criteria");
                        Row row1 = worksheet.getRow(0);
                        Cell cellA1 = row1.getCell((short) 0);
                        String a1Val = cellA1.getStringCellValue();


                        System.out.println("A1: " + a1Val);

                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                }

            }

finally I got the result:

enter image description here

temple
  • 964
  • 1
  • 12
  • 21
  • I tried you're exact code, and the binary. I am still getting the NullpointerException, what platform are you running on? Can the problem lie somewhere in the fact that I am using OSX? – Thizzer Aug 26 '13 at 09:57
  • I ran on windows7-64bit with eclipse 3.7.2 – temple Sep 03 '13 at 22:26
1

If you want to read .xlsx, could you please try this code (uses apache poi 3.9) :

    File file = new File("/app/app.xlsx");
    FileInputStream fs = new FileInputStream(file);
    OPCPackage xlsx = OPCPackage.open(fs);
    XSSFExcelExtractor xe = new XSSFExcelExtractor(xlsx);
    System.out.println(xe.getText());

The above code should display the content of the file app.xlsx.

user1234
  • 128
  • 4
  • 5
    If you have a `File` object, use it directly, don't wrap it in an InputStream! Using a File [requires less memory than an InputStream](http://poi.apache.org/spreadsheet/quick-guide.html#FileInputStream) – Gagravarr Aug 20 '13 at 12:30