Create a Simple Java/Maven Project to Read Excel
This tutorial will take you through how to use Java to read an Excel sheet and output its data.
Prerequisites:
Tutorial:
- Open Eclipse
- Create a new Maven project:
- File → New → Other → Maven Project
- Next
- Check “create a simple project”
- Next
- Give it a Group ID and Artifact ID
- Finish
- Add dependencies to the pom file for Apache POI-ooxml. The code for dependencies can be found at https://mvnrepository.com/ . Search "apache poi" and make sure to get the one with ooxml. (Note that you will need to surround the dependency in the pom file with <dependencies></dependencies>.)
- Under src/test/java, create a new class:
- Right-click on src/test/java
- New → Class
- Give it a name
- Check “public static main void” (if you miss this step, there’s another way to do it I’ll mention later)
- Click Finish
- Right-click on the class, and select “Properties” (you may have to scroll down)
- Click the button at the end of the “Location” line to open the directory in Explorer
- In that directory, create an Excel file (make sure it’s .xlsx)
- Fill the Excel file with data. For this tutorial, I am inputting this:
Pos. | Planet | Type |
1 | Mercury | Rocky |
2 | Venus | Rocky |
3 | Earth | Rocky |
4 | Mars | Rocky |
5 | Jupiter | Gas giant |
6 | Saturn | Gas giant |
7 | Uranus | Ice giant |
8 | Neptune | Ice giant |
- If you don’t have a main method in your java class, you can create one by typing main, then ctrl space, then selecting the main method.
- In the main method of your java class, create a String variable to hold the path and filename of your excel sheet (such as “./src/test/java/ExcelData.xlsx”). Note that “./” can be used to reference the project’s directory. String excelPath = "./src/test/java/ExcelData.xlsx";
- Initialize the excel workbook, using the String you created for the path: XSSFWorkbook workbook = new XSSFWorkbook(excelPath);
- Hover over XSSFWorkbook and import it from apache poi.
- Hover over again and surround with try/catch. Everything else we do will be within the try block.
- Get the first sheet in the excel file, using index 0: XSSFSheet sheet = workbook.getSheetAt(0);
- Hover over XSSFSheet and import it.
- Now, let’s get the total number of rows and store it into an integer variable: int totalRows = sheet.getPhysicalNumberOfRows();
- And we’ll get the number of columns, assuming the header row (the row with index 0) has a label for each used column: int totalCols = sheet.getRow(0).getLastCellNum();
- To print everything out to the console, let’s create a String: String text = "";
- Now, we want to loop through all the rows and columns. We’ll start by looping through the rows: for(int row = 0; row < totalRows; row++) {} This will increment the variable “row” from 0 to totalRows.
- To make the output pretty, let’s start each row with a pipe, a tab, and a space: text = "|\t ";
- If you don’t trust the rows to all have the same number of columns, you can move the “totalCols” line here, using your row variable as the index instead of 0, such as: int totalCols = sheet.getRow(row).getLastCellNum();
- Now we need to cycle through each column to get the cell data. We can do this with another for loop: for (int col = 0; col < totalCols; col++) {}
- To be able to read the data regardless of its type (String, integer, etc.), let’s use a data formatter: DataFormatter formatter = new DataFormatter ();
- Hover over DataFormatter to import it.
- Now we can extract the data into an object, using “row” and “col” as our indexes: Object value = formatter.formatCellValue(sheet.getRow(row).getCell(col));
- Let’s concatenate this onto our string, followed by another space, tab, pipe, and space. Note that we’ll need to convert the Object to a string, with .toString(): text += value.toString() + " \t| "; (If you use the same data in your Excel file as I did, it will look best with two spaces before the tab.)
- Now, outside the column “for” loop (but still within the row loop), print out the text line we’ve created: System.out.println(text);
- And we’re done! Running it should output the excel data into the console.
Note: Eclipse might complain that “workbook” is never closed. If you want, you can fix this by adding
workbook.close(); to the end of the “try” block, but this will throw errors at run time if you have the file open in Excel.
Your final file should look something like this: (I have commented out the close command, as well as the original totalCols line.)
--
SummerDale - 07 Oct 2020