Here is my piece of code for reading file in xlsx
and xls
format
File customerTemplateFileObj = new File(customerTemplateFullPath);
InputStream inputStream = new FileInputStream(customerTemplateFileObj);
Workbook myWorkBook = null;
try {
***myWorkBook = WorkbookFactory.create(inputStream);***
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int totalSheets = myWorkBook.getNumberOfSheets();
My code is working fine for xls
format but for xlsx
its stop at
myWorkBook = WorkbookFactory.create(inputStream);
without any Exception.
WorkbookFactory has a static method named “create(File file)” which creates the appropriate HSSFWorkbook / XSSFWorkbook from the given File, which must exist and be readable.
HSSFWorkbook − This class has methods to read and write Microsoft Excel files in . xls format. It is compatible with MS-Office versions 97-2003. XSSFWorkbook − This class has methods to read and write Microsoft Excel and OpenOffice xml files in .
public final class HSSFWorkbook extends POIDocument implements Workbook. High level representation of a workbook. This is the first object most users will construct whether they are reading or writing a workbook. It is also the top level object for creating new sheets/etc.
for reading xlsx file extion in java use XSSFWorkbook class from poi jar
package com.ssaurel.samples.excel;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ReadExcel {
public static void main(String[] args) throws IOException {
File excelFile = new File("contacts.xlsx");
FileInputStream fis = new FileInputStream(excelFile);
// we create an XSSF Workbook object for our XLSX Excel File
XSSFWorkbook workbook = new XSSFWorkbook(fis);
// ...
}
}
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