In this post under Apache Excel, I will show with example how to read an excel (*.xlsx) document.
Below is the complete code for your reference.
Main Class
1 package package2;
2
3 import java.io.File;
4 import java.io.IOException;
5
6 import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
7 import org.apache.poi.xssf.usermodel.XSSFCell;
8 import org.apache.poi.xssf.usermodel.XSSFRow;
9 import org.apache.poi.xssf.usermodel.XSSFSheet;
10 import org.apache.poi.xssf.usermodel.XSSFWorkbook;
11
12 public class Example2 {
13 public static void main(String[] args) throws IOException, InvalidFormatException {
14 File file = new File("Example2.xlsx");
15 try(XSSFWorkbook workbook = new XSSFWorkbook(file)) {
16 int numberOfSheets = workbook.getNumberOfSheets();
17 for(int i = 0; i < numberOfSheets; i++) {
18 XSSFSheet sheet = workbook.getSheetAt(i);
19 if(sheet.getFirstRowNum() != -1) {
20 for(int j = sheet.getFirstRowNum(); j <= sheet.getLastRowNum(); j++) {
21 XSSFRow row = sheet.getRow(j);
22 if(row.getFirstCellNum() != -1) {
23 for(int k = row.getFirstCellNum(); k < row.getLastCellNum(); k++) {
24 XSSFCell cell = row.getCell(k);
25 System.out.print(cell.getStringCellValue() + " ");
26 }
27 System.out.println();
28 }
29 }
30 }
31 }
32 }
33 }
34 }
In the above code, at line 14, we create a File object for “Example2.xlsx” file. Make sure it exists for reading.
At line 15, in try with resources block, we create an instance of “XSSFWorkbook” passing the file object as constructor argument.
At line 16, we get the number of sheets in the workbook by calling “getNumberOfSheets” methods on “workbook” instance.
At line 17, for each sheet in the workbook, we run the code between line 18 and 31.
At line 18, we get the “Sheet” instance at specific index by calling “getSheetAt” on “workbook” instance.
For each row in the sheet and for each column in the row, we run the code between 24 and 25.
We get a particular row in the sheet by calling “getRow” method on the “Sheet” instance. Refer to line 21.
We get a particular cell in a row, by calling “getCell” method on the “Row” instance. Refer to line 24.
We get the cell String value by calling “getStringCellValue” method on the specific cell. Refer to line 25.
We get the first and last row in the sheet by calling “getFirstRowNum” and “getLastRowNum”. Refer to line 20.
We get the first and last cell in the row by calling “getFirstCellNum” and “getLastCellNum”. Refer to line 23.
In this way we can read an existing worksheet.