Is there a way to determine MS Office Excel file type in Apache POI? I need to know in what format is the Excel file: in Excel '97(-2007) (.xls) or Excel 2007 OOXML (.xlsx).
I suppose I could do something like this:
int type = PoiTypeHelper.getType(file); switch (type) { case PoiType.EXCEL_1997_2007: ... break; case PoiType.EXCEL_2007: ... break; default: ... }
Thanks.
JButton btnFile = new JButton("Select Excel File"); btnFile. setPreferredSize(new Dimension(40, 40)); btnFile. addActionListener(new ActionListener() { // Handle open button action. public void actionPerformed(ActionEvent e) { final JFileChooser fc = new JFileChooser(); int returnVal = fc.
Apache POI is able to handle both XLS and XLSX formats of spreadsheets. Some important points about Apache POI API are: Apache POI contains HSSF implementation for Excel '97(-2007) file format i.e XLS. Apache POI XSSF implementation should be used for Excel 2007 OOXML (.
Promoting a comment to an answer...
If you're going to be doing something special with the files, then rjokelai's answer is the way to do it.
However, if you're just going to be using the HSSF / XSSF / Common SS usermodel, then it's much simpler to have POI do it for you, and use WorkbookFactory to have the type detected and opened for you. You'd do something like:
Workbook wb = WorkbookFactory.create(new File("something.xls"));
or
Workbook wb = WorkbookFactory.create(request.getInputStream());
Then if you needed to do something special, test if it's a HSSFWorkbook
or XSSFWorkbook
. When opening the file, use a File rather than an InputStream if possible to speed things up and save memory.
If you don't know what your file is at all, use Apache Tika to do the detection - it can detect a huge number of different file formats for you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With