Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WorkbookFactory.create(inputStream)

Tags:

java

excel

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.

like image 993
Amit Rai Avatar asked Apr 22 '16 05:04

Amit Rai


People also ask

What is WorkbookFactory create?

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.

What is the difference between HSSFWorkbook and XSSFWorkbook?

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 .

What is HSSFWorkbook in Java?

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.


1 Answers

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);

    // ...

  }

}
like image 66
Data Avatar answered Nov 02 '22 00:11

Data