×

Read the XLSX file in Java

Excel files contain cells; reading an excel file in Java differs from reading a word file. JDK doesn't have a direct API that can read or write Word or Excel documents. We must rely on Apache POI, a third-party library. t has numerous features, is widely used, and receives strong community support.

Apache POI

A Java API called Apache POI can read and write Microsoft Documents in both.xls and.xlsx format. Classes and interfaces are included.

For reading excel files, the Apache POI library offers two implementations:

  • Implementation of the HSSF (Horrible Spreadsheet Format) designates an API compatible with Excel 2003 or previous versions.
  • Implementation of XSSF (XML Spreadsheet Format): Indicates that an API is compatible with Excel 2007 or later versions.

Class and Interface used in Apache POI used for reading xlsx files

Classes

  • XSSFWorkbook is a class that symbolizes an XLSX file.
  • An XLSX file's sheet is represented by the class known as XSSFSheet.
  • The class XSSFRow stands for a row in an XLSX file's sheet.
  • The class XSSFCell represents a cell in a row of an XLSX file.

Interface

  • Workbook
    It serves as a representation of an Excel workbook. The workbook is an interface that the book and XSSFWorkbook have implemented. This Interface or sheet represents a worksheet in Excel. A workbook's main component, the sheet, represents a grid of cells. Java.lang.The Sheet interface extends Iterable.
  • Row
    It is a separate interface that depicts a spreadsheet row. Java.lang.The Row interface extends Iterable. The HSSFRow and XSSFRow concrete classes exist.
  • Cell
    It serves as an interface. Implementing Cell interfaces are HSSFCell and XSSFCell.

    Program for reading xlsx file in Java

ReadXLSX.java

// importing all necessary packages
import Java. io. File ;
import java. io . FileInputStream ;
import java . io . IOException ;
import org . apache . poi . hssf . usermodel . HSSFSheet ;
import org . apache . poi . hssf . usermodel . HSSFWorkbook ;
import org . apache . poi . ss . usermodel . Cell ;
import org . apache . poi . ss . usermodel . FormulaEvaluator ;
import org . apache . poi . ss . usermodel . Row ;
// Creating the main class with name ReadXLSX
public class ReadXLSX {
// Main section where execution starts
public static void main ( String [ ] args )
{
// using try block to prevent the stoppage of execution due to errors
try {
// creating object for the class FileInputStream to take the input from user i .e; xlsx file
FileInputStream f1 = new FileInputStream ( new File ( " example.xlsx " ) ) ;
// creating instance for workbook
XSSFWorkbook workbook1 = new XSSFWorkbook ( f1 ) ;
// creating instance for the class XSSFSheet
XSSFSheet st = workbook1 . getSheetAt ( 0 ) ;
// Using Iterator to iterate through the excel sheet
Iterator < Row > r = st . iterator ( ) ;
// Iterating over each row od the excel sheet
while ( r . hasNext ( ) ) {
// creating variable with name row for Row keyword to iterate through the sheet
Row row = r . next ( ) ;
Iterator < Cell > c = row . cellIterator ( ) ;
// Itearator to iterate each column
while ( c . hasNext ( ) ) {
Cell cell = c . next ( ) ;
// using the switch case 
switch ( cell . getCellType ( ) ) 
{
case Cell . CELL_TYPE_NUMERIC :
System . out . print ( cell . getNumericCellValue ( ) + "t" ) ;
break ;
// if the cell contains string value
case Cell . CELL_TYPE_STRING :
System . out . print ( cell . getStringCellValue ( ) + ) ;
break ;
}
}
System . out . println ( " " ) ;
}
// open excel file should be closed
f1 . close ( ) ;
}
// if Exception is raised, it is caught here 
// Exception is the main class which contains all the predefined exceptions in it
catch ( Exception e ) {
e . printStackTrace ( ) ;
}
}
}

Output

Read the XLSX file in Java

Related Topics

User Defined Custom Exceptions in Java

In this tutorial, we will discuss user-defined custom exceptions with examples. Introduction In Java, we have proactively characterised, Exception classes, for example, ArithmeticException, NullPointerException, ArrayoutOfBound and so on. These built-in exceptions are...

3 minutes read.

Program to find the duplicate characters in a string

Problem statement You have given with a string and your task is to find out the repeated characters from the string and print them. If no character is repeated, then you...

2 minutes read.

Group by in Java 8

By using this groupingBy() method, developers can directly able to perform the "GROUP BY" operation. The thing is, now, the Java 8 programming language allows the programmers to do this...

3 minutes read.

How to Convert boolean to String in Java

How to Convert boolean to String in Java There are two methods to convert boolean to String. Using valueOf(boolean) method Using toString(boolean) method For both the above methods, if the passes Boolean...

2 minutes read.

Java Integer compareTo() method

The compareTo() method of Integer class compares two Integer objects numerically. Syntax public static int compareTo(int anotherInteger) Parameters The parameter ‘anotherInteger’ represents the Integer to be compared. Specified by This method is specified by compareTo in...

2 minutes read.

Java Integer longValue() method

The longValue()  method of Java Integer class returns a long value for this Integer after a widening primitive conversion. Syntax public long longValue() Parameters NA Specified by This method is specified by longValue in class Number Return...

1 minute read.

Grepcode Java util date

What is java.util.Date Class? The date and time in Java are provided through the java.util.Date class. If you imported java.util, it could be helpful. Use the Java.util.Date class to implement this class...

4 minutes read.

Java vs Golang

Java Java is both a programming language and a platform. Java is a high-level, dependable, object-oriented, and secure programming language. Java was developed in 1995 by Sun Microsystems, which is now an...

4 minutes read.

Java file Writer

File Writer: It is used to write all the data from text files. It inherits the properties from the Output Stream class. It is meant for writing characters. It is meant...

4 minutes read.

Program to check whether a given character is present in a string or not

In this article, you will understand the logic to find out whether the given character is present in the string or not and find out the position of the specified...

3 minutes read.

Internal Working of ArrayList in Java

Java's version of a resizable array is called ArrayList. The dynamic growth of an array list ensures that there is always room for new elements. ArrayList's backing data structure is...

8 minutes read.

String Array in Java

String Array in Java An array is alinear data structure that stores similar type of data. It allows us to store fixed number of elements.It can be of different data types...

6 minutes read.

Java Do While Loop

When we wish to test the exit condition at the end of the loop, we use a do-while loop. The do-while loop always executes its body at least once, because...

1 minute read.

Java Math ulp() Method

The ulp() method of Java Math class returns the size of an ulp of the argument. Syntax: public static double ulp(double x)public static float ulp(float x) Parameters: The parameter ‘x’ represents the floating-point number...

2 minutes read.

Java Externalization

What is Externalization in Java? Externalization is a concept that is advanced to serialization. Serialization is a concept where we can transfer an object from our JVM ( Java virtual machine...

3 minutes read.

Minimum XOR value pair in Java

In this section, you will discuss about minimum XOR value pair in Java. The objective is to enforce a value that indicates the least XOR values of the two numbers from...

4 minutes read.

Java Integer highestOneBit()

The highestOneBit() method of Java Integer class returns an int value with at most a single one-bit, in the position of the highest-order one-bit in the specified int value.  Syntax public static...

1 minute read.

Sorting Algorithms in Java

Sorting Algorithms in Java Sorting is the technique that puts the elements of an array or list either in descending or ascending order. For example, take an array A, whose elements...

3 minutes read.

List of Constants in Java

In this tutorial, we are going to deal with constants available in Java.Every programming language has its constants. Similarly, Javaalso has got constants of its own. In this tutorial, we will...

6 minutes read.

Sleeping Barber Problem in Java

The barbershop in this issue has one barber, one barber chair, and N chairs for customers in the waiting area. We may demonstrate the issue by keeping with the original...

6 minutes read.