Nikolay Baranenko Nikolay Baranenko - 1 year ago 80
Java Question

Why does not load infomation from excel (*.xlsx) (use Apache POI)?

Try to load information on JSP from Excel file (*.xlsx) use Apache POI 3.15.

View information in excel

num solution

1 First

2 Second

3 Third

try to use code

try {
InputStream ExcelFileToRead = new FileInputStream("C:\\server\\to_db.xlsx");
XSSFWorkbook wb = new XSSFWorkbook(ExcelFileToRead);

XSSFWorkbook test = new XSSFWorkbook();

XSSFSheet sheet = wb.getSheetAt(0);
XSSFRow row;
XSSFCell cell;

Iterator rows = sheet.rowIterator();

while (rows.hasNext()) {
row = (XSSFRow);
Iterator cells = row.cellIterator();
while (cells.hasNext()) {
cell = (XSSFCell);

if (cell.getCellType() == XSSFCell.CELL_TYPE_STRING) {
out.print(cell.getStringCellValue() + " ");
} else if (cell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC) {
out.print(cell.getNumericCellValue() + " ");
} else {
//U Can Handel Boolean, Formula, Errors
catch (Exception e) {
out.println( "exception: "+e);

Getting a strange result:

absent error and absent information on JSP....

Problem problem is reproduced in all browsers.
If I try open C:\server\to_db.xlsx OS Windows responce "File is busy".
What could be the problem and how to solve it?

Answer Source

When you open a FileInputStream or FileOutputStream, you need to close it otherwise your file could be locked by the process according to the OS used especially on Windows OS. More generally speaking, you need to close all Closeable objects that you use to prevent any leaks or issues like this one.

So you should rewrite your code as next to use the try-with-resources statement that will automatically close the resources for you.

try (InputStream ExcelFileToRead = new FileInputStream("C:\\server\\to_db.xlsx");
     XSSFWorkbook wb = new XSSFWorkbook(ExcelFileToRead)) {

Indeed in your code you have 2 Closeable objects which are ExcelFileToRead and wb.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download