I just have a quick question about how to read in an xlsx file using the XSSF format from Apache.
Right now my code looks like this:
InputStream fs = new FileInputStream(filename); // (1)
XSSFWorkbook wb = new XSSFWorkbook(fs); // (2)
XSSFSheet sheet = wb.getSheetAt(0); // (3)
...with all the relevant things imported. My problem is that when I hit run, it gets stuck at line (2), in almost an infinite loop. filename
is just a string.
If anybody could give me some sample code on how to fix this I would really appreciate it. All i want right now is to read in a single cell from an xlsx file; I was using HSSF for xls files and had no problems.
Thanks for your help, Andrew
XSSF is the POI Project's pure Java implementation of the Excel 2007 OOXML (. xlsx) file format. HSSF and XSSF provides ways to read spreadsheets create, modify, read and write XLS spreadsheets.
In Java, reading an Excel file is not similar to reading a Word file because of cells in an Excel file. JDK does not provide a direct API to read data from Excel files for which we have to toggle to a third-party library that is Apache POI.
I bealive that this will answer your questions: http://poi.apache.org/spreadsheet/quick-guide.html#ReadWriteWorkbook
In short, your code should look like this:
InputStream inp = new FileInputStream("workbook.xlsx");
Workbook wb = WorkbookFactory.create(inp);
Sheet sheet = wb.getSheetAt(0);
Row row = sheet.getRow(2);
Cell cell = row.getCell(3);
InputStream inp = null;
try {
inp = new FileInputStream("E:/sample_poi.xls");
Workbook wb = WorkbookFactory.create(inp);
Sheet sheet = wb.getSheetAt(0);
Header header = sheet.getHeader();
int rowsCount = sheet.getLastRowNum();
System.out.println("Total Number of Rows: " + (rowsCount + 1));
for (int i = 0; i <= rowsCount; i++) {
Row row = sheet.getRow(i);
int colCounts = row.getLastCellNum();
System.out.println("Total Number of Cols: " + colCounts);
for (int j = 0; j < colCounts; j++) {
Cell cell = row.getCell(j);
System.out.println("[" + i + "," + j + "]=" + cell.getStringCellValue());
}
}
} catch (Exception ex) {
java.util.logging.Logger.getLogger(FieldController.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
inp.close();
} catch (IOException ex) {
java.util.logging.Logger.getLogger(FieldController.class.getName()).log(Level.SEVERE, null, ex);
}
}
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