Tarun Arora
Tarun Arora

Reputation: 123

Error reading excel file

Below is the code:-

    try {
        ByteArrayInputStream bis = new ByteArrayInputStream(file.getBytes());
        if (file.getOriginalFilename().endsWith(Constants.XLS_EXTENSION)) {
            return new HSSFWorkbook(bis);
        } else if (file.getOriginalFilename().endsWith(Constants.XLSX_EXTENSION)) {
            return new XSSFWorkbook(bis);
        } else {
            throw new IllegalArgumentException("Received file does not have a standard excel extension.");
        }
    } catch (IOException | IllegalArgumentException e) {
        log.error("Exception while reading the file", e);
    }
    return null;

getting error while reading the xls format file.

Below is the exception:-

2016-05-27 11:48:24 --- [http-nio-6060-exec-1] ERROR com.atms.web.rest.controllers.TestCaseResource:912 - Exception while reading the file

java.io.IOException: Unable to read entire header; 181 bytes read; expected 512 bytes

Upvotes: 0

Views: 1297

Answers (1)

jmarkmurphy
jmarkmurphy

Reputation: 11473

I have not seen the ByteArrayInputStream used before for this. Are you sure it isn't the problem?

From the Quick Guide: https://poi.apache.org/spreadsheet/quick-guide.html#FileInputStream

// Use a file
Workbook wb = WorkbookFactory.create(new File("MyExcel.xls"));

// Use an InputStream, needs more memory
Workbook wb = WorkbookFactory.create(new FileInputStream("MyExcel.xls"));

If using HSSFWorkbook or XSSFWorkbook directly, you should generally go through NPOIFSFileSystem or OPCPackage, to have full control of the lifecycle (including closing the file when done):

// HSSFWorkbook, File
NPOIFSFileSystem fs = new NPOIFSFileSystem(new File("file.xls"));
HSSFWorkbook wb = new HSSFWorkbook(fs.getRoot(), true);
....
fs.close();

// HSSFWorkbook, InputStream, needs more memory
NPOIFSFileSystem fs = new NPOIFSFileSystem(myInputStream);
HSSFWorkbook wb = new HSSFWorkbook(fs.getRoot(), true);
....
fs.close();

Try one of these, and then if you still have problems, we can look into the possibility of other issues.

Upvotes: 2

Related Questions