- Reading Values From Excel in Java
- 1. Overview
- 2. Maven Dependency
- 3. Apache POI Overview
- 3.1. Handling Excel Files
- 3.2. Iterating Through the Excel File
- 3.3. Reading Cell Values in Excel
- 4. Conclusion
- How to Get a Specific Cell Value in Excel using Java
- Java Excel reader library — installation#
- Read a specific Excel cell value using Java reader #
- Get an Excel cell value with formatting in Java#
- Get a free license#
- Conclusion#
- Ask a question#
- See also#
Reading Values From Excel in Java
The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.
To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.
Connect your cluster and start monitoring your K8s costs right away:
We rely on other people’s code in our own work. Every day.
It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.
The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.
Lightrun is a new kind of debugger.
It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.
Learn more in this quick, 5-minute Lightrun tutorial:
Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.
The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.
Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.
Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:
DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.
The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.
And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.
The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.
To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.
Connect your cluster and start monitoring your K8s costs right away:
We’re looking for a new Java technical editor to help review new articles for the site.
1. Overview
When it comes to Microsoft Excel files, reading values from different cells can be a little tricky. Excel files are spreadsheets organized in rows and cells which can contain String, Numeric, Date, Boolean, and even Formula values. Apache POI is a library offering a full suite of tools to handle different excel files and value types.
In this tutorial, we’ll focus on learning how to handle excel files, iterate through rows and cells, and use the proper way to read each cell value type.
2. Maven Dependency
Let’s start by adding the Apache POI dependency to pom.xml:
org.apache.poi poi-ooxml 5.2.0
The latest versions of poi-ooxml can be found at Maven Central.
3. Apache POI Overview
The hierarchy starts with the workbook, which represents the whole Excel File. Each file can contain one or more worksheets, which are collections of rows and cells. Depending on the version of the excel file HSSF is the prefix of the classes representing the old Excel files (.xls), whereas the XSSF is used for the newest versions (.xlsx). Therefore we have:
- XSSFWorkbook and HSSFWorkbook classes represent the Excel workbook
- Sheet interface represents Excel worksheets
- The Row interface represents rows
- The Cell interface represents cells
3.1. Handling Excel Files
First, we open the file we want to read and convert it into a FileInputStream for further processing. FileInputStream constructor throws a java.io.FileNotFoundException so we need to wrap it around a try-catch block and close the stream at the end:
public static void readExcel(String filePath) < File file = new File(filePath); try < FileInputStream inputStream = new FileInputStream(file); . inputStream.close(); >catch (IOException e) < e.printStackTrace(); >>
3.2. Iterating Through the Excel File
After we successfully open the InputStream it’s time to create the XSSFWorkbook and iterate through the rows and cells of each sheet. In case we know the exact number of sheets or the name of a specific sheet, we can use the getSheetAt(int index) and getSheet(String sheetName) methods of XSSFWorkbook, respectively.
Since we want to read through any kind of Excel file, we’ll iterate through all the sheets using three nested for loops, one for the sheets, one for the rows of each sheet, and finally one for the cells of each sheet.
For the sake of this tutorial we will only print the data to the console:
FileInputStream inputStream = new FileInputStream(file); Workbook baeuldungWorkBook = new XSSFWorkbook(inputStream); for (Sheet sheet : baeuldungWorkBook)
Then, in order to iterate through the rows of a sheet, we need to find the index of the first row and the last row which we get from the sheet object:
int firstRow = sheet.getFirstRowNum(); int lastRow = sheet.getLastRowNum(); for (int index = firstRow + 1; index
Finally, we do the same for the cells. Also, while accessing each cell we can optionally pass down a MissingCellPolicy which basically tells the POI what to return when a cell value is empty or null. The MissingCellPolicy enum contains three enumerated values:
The code for the cell iteration is as follows:
for (int cellIndex = row.getFirstCellNum(); cellIndex
3.3. Reading Cell Values in Excel
As we mentioned before, Microsoft Excel’s cells can contain different value types, so it’s important to be able to distinguish one cell value type from another and use the appropriate method to extract the value. Below there’s a list of all the value types:
We’ll focus on four main cell value types: Numeric, String, Boolean, and Formula, where the last one contains a calculated value that is of the first three types.
Let’s create a helper method that basically will check for each value type and based on that it’ll use the appropriate method to access the value. It’s also possible to treat the cell value as a String and retrieve it with the corresponding method.
There are two important things worth noting. First, Date values are stored as Numeric values, and also if the cell’s value type is FORMULA we need to use the getCachedFormulaResultType() instead of the getCellType() method to check the result of Formula’s calculation:
public static void printCellValue(Cell cell) < CellType cellType = cell.getCellType().equals(CellType.FORMULA) ? cell.getCachedFormulaResultType() : cell.getCellType(); if (cellType.equals(CellType.STRING)) < System.out.print(cell.getStringCellValue() + " | "); >if (cellType.equals(CellType.NUMERIC)) < if (DateUtil.isCellDateFormatted(cell)) < System.out.print(cell.getDateCellValue() + " | "); >else < System.out.print(cell.getNumericCellValue() + " | "); >> if (cellType.equals(CellType.BOOLEAN)) < System.out.print(cell.getBooleanCellValue() + " | "); >>
Now, all we need to do is call the printCellValue method inside the cell loop and we are done. Here’s a snippet of the full code:
. for (int cellIndex = row.getFirstCellNum(); cellIndex < row.getLastCellNum(); cellIndex++) < Cell cell = row.getCell(cellIndex, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK); printCellValue(cell); >.
4. Conclusion
In this article, we have shown an example project for reading Excel files and accessing different cell values using Apache POI.
The full source code can be found over on GitHub.
Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.
The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.
Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.
Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:
How to Get a Specific Cell Value in Excel using Java
Excel (XLSX or XLS) workbooks are widely used by large to small-scale organizations for financial data analysis, record keeping, and organizing data. An Excel file consists of one or multiple spreadsheets, and a sheet contains a grid of cells. As a Java developer, you might have a requirement to use the existing Excel file data in your application, and you are finding an easy way to read the value of a particular cell. To deal with it, we will discuss how to get a specific cell value in Excel using Java. Furthermore, we will see how to read a cell value as a string with or without formatting.
The following points will be covered in this article:
Java Excel reader library — installation#
In this section, we will discuss the procedure of this Java Excel reader library. If you are using Maven to manage a Java project or app, add the following configurations in the pom.xml file.
ConholdateJavaAPI Conholdate Java API https://releases.conholdate.com/java/repo com.conholdate conholdate-total 23.6 pom
Then run the following commands.
For configurations about other Java frameworks, please visit releases.conholdate.com.
Read a specific Excel cell value using Java reader #
This section demonstrates how to get a specific cell value in Excel worksheet. Since each cell’s location is identified by the reference of an intersection of row number and column letter, the cell’s identity should be kept in mind before opening the code editor. Suppose we need to get the value of the “G5” cell.
To read the cell value, follow the steps given below:
- Load Excel file using Workbook class.
- Obtain the reference of desired cell in a Worksheet object using Worksheet.getCells().get(String cellName) method.
- Read and display cell value using Cell.getValue() method.
The following code sample shows how to get and display an Excel cell value in Java.
Get an Excel cell value with formatting in Java#
So far, we have explained how to read a particular Excel cell value using the Java Excel reader library. By adding more, we will describe how to read the string value of a cell with or without formatting. Please follow the steps given below:
- First, load the Excel file using Workbook class.
- Then, get the reference of desired cell in a Worksheet object using Worksheet.getCells().get(String cellName) method.
- Finally, print cell value with the applied style using Cell.getStringValue(CellValueFormatStrategy.CELL_STYLE) method.
- Optionally, you can print cell value without style using Cell.getStringValue(CellValueFormatStrategy.NONE) method.
The following code snippet shows how to get and print a cell value with or without formatting in Java. Suppose “0.12345” is a cell value, the output will be displayed as follows:
Value with cell style: 0.12 Value without any formatting: 0.12345
Get a free license#
You can get a free temporary license to try the API without evaluation limitations.
Conclusion#
To conclude, we hope you have learned how to get the value of a particular cell in Excel in Java using an Excel reader library. Furthermore, you have gone through how to obtain the cell value as a string with or without cell formatting.
You may visit the documentation to learn more about the Java Excel reader API.
Finally, please stay tuned at conholdate.com for regular updates.
Ask a question#
You can let us know your questions or queries on our forum.