Search code examples
javaeclipsexlsx

Need to access data from xlsx file


public class fileReader {

    public static void main (String[] args) throws IOException {
        String excelFilePath = "sample.xlsx";
        InputStream inputStream = new FileInputStream(new File(excelFilePath));

        XSSFWorkbook workbook = new XSSFWorkbook();
        Sheet firstSheet = workbook.getSheetAt(0);
        Iterator<Row> iterator = firstSheet.iterator();

        while (iterator.hasNext()) {
            Row nextRow = iterator.next();
            Iterator<Cell> cellIterator = nextRow.cellIterator();
        ...

In the XSSFWorkbook line the error has been showing

Exception in thread "main" org.apache.poi.ooxml.POIXMLException: org.apache.xmlbeans.XmlOptions.setEntityExpansionLimit(I)Lorg/apache/xmlbeans/XmlOptions;
    at org.apache.poi.ooxml.POIXMLFactory.createDocumentPart(POIXMLFactory.java:66)
    at org.apache.poi.ooxml.POIXMLDocumentPart.read(POIXMLDocumentPart.java:657)
    at org.apache.poi.ooxml.POIXMLDocument.load(POIXMLDocument.java:180)
    at org.apache.poi.xssf.usermodel.XSSFWorkbook.<init>(XSSFWorkbook.java:282)
    at org.apache.poi.xssf.usermodel.XSSFWorkbook.<init>(XSSFWorkbook.java:303)
    at fileReader.main(fileReader.java:20)

Solution

  • You are not reading your file. You are creating a new workbook. SO I suspect your are getting an exception because your are asking for a Sheet where there is none.

    Provide your file to the instance using XSSFWorkbook(File)

    String excelFilePath = "sample.xlsx";
    File f = new File(excelFilePath);
    XSSFWorkbook workbook = new XSSFWorkbook(f);
    

    Or XSSFWorkbook(InputStream)

    String excelFilePath = "sample.xlsx";
    File f = new File(excelFilePath);
    InputStream inputStream = new FileInputStream(f);
    XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
    

    If File is given to the workbook instance then there occurs an error showing File cannot be resolved to a type

    Just need to import java.io.File