Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine MS Excel file type with Apache POI

Tags:

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.

like image 674
Alexey Berezkin Avatar asked Jan 25 '13 13:01

Alexey Berezkin


People also ask

How do I know if I have an XLSX or XLS file in Java?

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.

Does Apache POI support Xlsx?

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 (.


1 Answers

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.

like image 125
Gagravarr Avatar answered Oct 04 '22 03:10

Gagravarr