SlideShare a Scribd company logo
How to Read Excel Files in
Java?
In today’s computer world, excel files are an integral part of every business ranging
from small to large. The uses of Excel files include data management, analysis,
charting, graphing, etc. So when we come to the programming side, there will be a
situation where we have to handle Excel files. In Java programming, there is no
built-in feature to support Excel files. Yet we can handle Excel files easily by using
the third-party API named Apache POI. In today’s article, we will look at how to read
Excel files in Java using the Apache POI API.
Excel files:
We all know that Excel files are spreadsheets that make data handling and
manipulation easier.
Generally, there are two file formats available for Excel files. They are
1. .xls
2. .xlsx.
The xls format is the older one for 2003 and older versions. And xlsx is a new format
for excel 2007 and later.
Apache POI:
Generally, Apache POI (Poor Obfuscation Implementation) is an open-source library
for handling Microsoft office related files. Java does not have the built-in feature to
handle excel files. So, We use Apache POI, a third-party Java API with classes and
interfaces to deal with reading and writing operations in excel files.
This API supports both .xls and .xlsx formats. To deal with the .xls format, we use
HSSF(Horrible SpreadSheet Format) implementation. And to deal with the .xlsx
format, we use XSSF(XML SpreadSheet Format) implementation.
Classes:
We all know that Excel files consist of Workbook, WorkSheets, cells, rows, and
columns. The API comprises a variety of classes to incorporate the functionality that
deals with excel files. There are separate classes available to deal with .xls and .xlsx
formats.
HSSFWorkbook, HSSFSheet, HSSFRow, and HSSFCell are the classes that
provide the functionality for handling workbooks, sheets, rows, and cells in xls format
files, respectively.
Similarly, the XSSFWorkbook, XSSFSheet, XSSFRow, and XSSFCell are the
classes that provide the functionality for handling workbooks, sheets, rows, and cells
in xlsx format files, respectively.
Interface:
This API provides some common interfaces for all the classes discussed above.
They are:
1. Workbook – Workbook is a common interface implemented by both
HSSFWorkbook and XSSFWorkbook classes.
2. Sheet – The HSSFSheet and XSSFSheet classes implement this interface.
3. Row – Both HSSFRow and XSSFRow classes use this interface.
4. Cell – The HSSFCell and XSSFCell classes implement this interface.
Prerequisites for using ApachePOI to
read excel file in java:
The requirements for using ApachePOI are:
1. An eclipse IDE
2. poi-bin-5.2.3-20220909.zip folder
Extract the zip file. There is a list of jar files required to use ApachePOI.
You can download the latest versions of the jar if needed.
3. An excel file in both formats.
a. In this article, we will use the excel files named FirstCode.xls and FirstCode.xlsx.
b. The content of the files are:
Now follow the steps given below to set up the environment.
1. Open the Eclipse IDE
2. Create a new java project.
3. Add all the downloaded jar files in the classpath, as shown below.
Right-click the project name→ Build Path → Configure Build Path → Click the
libraries tab → Add External jars in Classpath → Select all the jars discussed above
→ Click Apply and close. If you are using maven, you should include the following
dependencies in your pom.xml file.
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>5.2.0</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.2.0</version>
</dependency>
Code to read the xls file in java:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
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;
public class ReadExcelFile {
public static void main(String args[])
{
try {
//Creating a file object and getting the excel file.
File file= new File("E:FirstCode.xls");
// Creating FileInputStream object to read the file.
FileInputStream fisObject=new FileInputStream(file);
//Creating Workbook instance for .xls file.
HSSFWorkbook workbook=new HSSFWorkbook(fisObject);
//Getting the sheet number from the user.
System.out.println("Enter the sheet number:");
Scanner scan = new Scanner(System.in);
int sheetnumber = scan.nextInt();
//Creating a Sheet object to get the required sheet in the file.
HSSFSheet sheet=workbook.getSheetAt(sheetnumber);
//Evaluating cell type
FormulaEvaluator
formulaEvaluator=workbook.getCreationHelper().createFormulaEvaluator();
//Iterating the rows with, for each loop.
for(Row row: sheet)
{
//Iterating the cells with, for each loop.
for(Cell cell: row)
{
switch(formulaEvaluator.evaluateInCell(cell).getCellType())
{
//Numeric cell type.
case NUMERIC:
//Getting the cell value as a number and printing it.
System.out.print(cell.getNumericCellValue()+ "tt");
break;
//String cell type.
case STRING:
//Getting the cell value as a string and printing it.
System.out.print(cell.getStringCellValue()+ "tt");
break;
default:
break;
}
}
System.out.println();
}
workbook.close();
}
catch(FileNotFoundException exception) {
//If there is no excel file with the given name found in the specified location, it
throws FileNotFoundException.
System.out.println("File Not Found.");
}
catch(IllegalArgumentException exception) {
//If the sheet is empty, it throws an IllegalArgumentException.
System.out.println("Sheet is empty");
}
catch(Exception exception) {
//To deal with other Exceptions.
exception.printStackTrace();
}
}
}
Output:
■ When the excel file reading is successful, whole file will be displayed as
output.
■ When there is no excel file with the given name found in the specified
location, the output will be:
File Not Found
■ When there is no data in the given sheet index, the output will be:
Sheet is empty
Code to read the xlsx file in java:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Iterator;
import java.util.Scanner;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ReadExcelFile
{
public static void main(String[] args)
{
try
{
//Creating a file object and getting the excel file.
File file = new File("E:FirstCode.xlsx");
// Creating FileInputStream object to read the file.
FileInputStream fisObject = new FileInputStream(file);
//Creating Workbook instance for .xlsx file.
XSSFWorkbook workbook = new XSSFWorkbook(fisObject);
//Getting the sheet number from the user.
System.out.println("Enter the sheet number:");
Scanner scan = new Scanner(System.in);
int sheetnumber = scan.nextInt();
//Creating a Sheet object to get the required sheet in the file.
XSSFSheet sheet = workbook.getSheetAt(sheetnumber);
//Using an iterator to iterate the sheet object to get rows.
Iterator<Row> itr = sheet.iterator();
while (itr.hasNext())
{
// Getting the row values.
Row row = itr.next();
//Iterating each column in the row.
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext())
{
//Getting column values.
Cell cell = cellIterator.next();
//Getting cell type.
switch (cell.getCellType())
{
//String cell type.
case STRING:
//Getting the cell value as a string and printing it.
System.out.print(cell.getStringCellValue() + "ttt");
break;
//Numeric cell type.
case NUMERIC:
//Getting the cell value as a number and printing it.
System.out.print(cell.getNumericCellValue() + "ttt");
break;
default:
break;
}
}
System.out.println("");
}
workbook.close();
}
catch(FileNotFoundException exception)
{
//If there is no excel file with the given name found in the specified location, it
throws FileNotFoundException.
System.out.println("File Not Found.");
}
catch(IllegalArgumentException exception)
{
//If the sheet is empty, it throws an IllegalArgumentException.
System.out.println("Sheet is empty");
}
catch(Exception exception)
{
//To deal with other Exceptions.
exception.printStackTrace();
}
}
}
Output:
■ When the excel file reading is successful, the output will be the whole file.
■ When there is no excel file with the given name found in the specified
location, the output will be:
File Not Found
■ When there is no data in the given sheet index, the output will be:
Sheet is Empty
Code to read a particular cell value in the
xlsx file in Java:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ReadExcelFile {
public static void main(String[] args)
{
//Creating an object for the ReadExcelFile class.
ReadExcelFile rc=new ReadExcelFile();
System.out.println("Enter the sheet, row, and column number of the cell:");
//Getting the input for sheet, row, and column number, from the user.
Scanner scan = new Scanner(System.in);
int sheetnumber = scan.nextInt();
int row = scan.nextInt();
int column = scan.nextInt();
//ReadCellData function call
String vOutput=rc.ReadCellData(row, column, sheetnumber);
//Checking whether the return value is null. The method returns null when the sheet or
cell is empty.
if(vOutput!=null)
//Printing the cell value.
System.out.println(vOutput);
}
//Method for getting the cell value.
public String ReadCellData(int vRow, int vColumn, int vsheet)
{
//Variable to store the cell value.
String value=null;
//Initializing Workbook object as null.
Workbook workbook=null;
try
{
// Creating FileInputStream object to read the file.
FileInputStream fis=new FileInputStream("E:FirstCode.xlsx");
//Creating Workbook instance for .xls file.
workbook=new XSSFWorkbook(fis);
//Creating a Sheet object to get the required sheet in the file.
Sheet sheet=workbook.getSheetAt(vsheet);
// Getting the specified row.
Row row=sheet.getRow(vRow);
// Getting the specified column.
Cell cell=row.getCell(vColumn);
// Getting the specified cell value.
value=cell.getStringCellValue();
}
catch(FileNotFoundException exception)
{
//If there is no excel file with the given name found in the specified location, it
throws FileNotFoundException.
System.out.println("File Not Found.");
}
catch(IOException exception)
{
System.out.println("Invalid inputs.");
}
catch(NullPointerException exception)
{
//If the cell is empty, it throws a NullPointerException.
System.out.println("No data in the specified cell");
}
catch(IllegalArgumentException exception)
{
//If the sheet is empty, it throws an IllegalArgumentException.
System.out.println("Empty sheet");
}
catch(Exception exception)
{
//To deal with other Exceptions.
exception.printStackTrace();
}
// Returns the corresponding cell value.
return value;
}
}
Output:
■ When the excel file reading is successful, the output will be the desired
value.
■ When there is no excel file with the given name found in the specified
location, the output will be:
File Not Found
■ When there is no data in the given sheet index, the output will be:
Empty Sheet
■ When there is no data in the given cell, the output will be:
No data in the specified cell
Code to read xls and xlsx files in java:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
public class ReadExcelFile {
public static final String FILE_PATH = "E:FirstCode.xlsx";
public static void main(String[] args) {
try {
//Creating Workbook instance for excel file for both format .xls and .xlsx file.
Workbook workbook = WorkbookFactory.create(new File(FILE_PATH));
// Getting the number of sheets in the Workbook.
System.out.println("Workbook consists of " + workbook.getNumberOfSheets() + " Sheets :
");
System.out.println("Enter the sheet index number:");
//Getting the sheet number from the user.
Scanner scan = new Scanner(System.in);
int sheetnumber = scan.nextInt();
//Creating a Sheet object to get the required sheet in the file.
Sheet sheet = workbook.getSheetAt(sheetnumber);
// Create a DataFormatter to format each cell value as String.
DataFormatter dataFormatter = new DataFormatter();
//Using forEach loop with lambda(Java8).
sheet.forEach(row -> {
row.forEach(cell -> {
String cellValue = dataFormatter.formatCellValue(cell);
System.out.print(cellValue + "tt");
});
System.out.println();
});
// Closing the workbook object.
workbook.close();
}
catch(FileNotFoundException exception)
{
//If there is no excel file with the given name found in the specified location, it
throws FileNotFoundException.
System.out.println("File Not Found.");
}
catch(IllegalArgumentException exception)
{
//If the sheet is empty, it throws an IllegalArgumentException.
System.out.println("Sheet is empty");
}
catch(Exception exception)
{
//To deal with other Exceptions.
exception.printStackTrace();
}
}
}
Output:
■ When the excel file reading is successful, the output will be as desired.
■ When there is no Excel file with the given name found in the specified
location, the output will be:
File not Found
■ When there is no data in the given sheet index, the output will be:
Sheet is Empty
Additional tips:
If your excel file has more than one sheet, you can get the number of sheets and
iterate over them. Refer to the code snippet for a better understanding.
Code snippet:
workbook.forEach(sheet -> {
System.out.println("=> " + sheet.getSheetName());
});
To iterate among the sheets or rows, or cells, you can use one of the following ways:
1. for each loop with a lambda expression.
2. for each loop
3. Iterator
I demonstrated each iterating way in the sample codes above for your reference.
Summary
There is another API for handling excel files named JXL or JEXCEL. But this API
supports only xls files and does not support xlsx files. Its last update was in 2009. So
everyone uses ApachePOI now. I hope you understand how to use ApachePOI to
read excel files in java. Thank you for reading.

More Related Content

Similar to How to Read Excel Files in Java (1).pdf

Hands On Intro to Node.js
Hands On Intro to Node.jsHands On Intro to Node.js
Hands On Intro to Node.js
Chris Cowan
 
CS101S. ThompsonUniversity of BridgeportLab 7 Files, File.docx
CS101S. ThompsonUniversity of BridgeportLab 7 Files, File.docxCS101S. ThompsonUniversity of BridgeportLab 7 Files, File.docx
CS101S. ThompsonUniversity of BridgeportLab 7 Files, File.docx
annettsparrow
 
7 Data File Handling
7 Data File Handling7 Data File Handling
7 Data File Handling
Praveen M Jigajinni
 
Filesin c++
Filesin c++Filesin c++
Filesin c++
HalaiHansaika
 
Import and Export Excel Data using openxlsx in R Studio
Import and Export Excel Data using openxlsx in R StudioImport and Export Excel Data using openxlsx in R Studio
Import and Export Excel Data using openxlsx in R Studio
Rupak Roy
 
UNIT 5.pptx
UNIT 5.pptxUNIT 5.pptx
InstructionYou’ll probably want to import FileReader, PrintWriter,.pdf
InstructionYou’ll probably want to import FileReader, PrintWriter,.pdfInstructionYou’ll probably want to import FileReader, PrintWriter,.pdf
InstructionYou’ll probably want to import FileReader, PrintWriter,.pdf
arsmobiles
 
APPLICATION TO DOCUMENT ALL THE DETAILS OF JAVA CLASSES OF A PROJECT AT ONCE...
APPLICATION TO DOCUMENT ALL THE  DETAILS OF JAVA CLASSES OF A PROJECT AT ONCE...APPLICATION TO DOCUMENT ALL THE  DETAILS OF JAVA CLASSES OF A PROJECT AT ONCE...
APPLICATION TO DOCUMENT ALL THE DETAILS OF JAVA CLASSES OF A PROJECT AT ONCE...
DEEPANSHU GUPTA
 
Class 1
Class 1Class 1
Class 1
Dario Pilozo
 
Class 1
Class 1Class 1
Class 1
Dario Pilozo
 
Filehandling
FilehandlingFilehandling
Filehandling
Muhammad Fahad
 
ELF
ELFELF
Best Of Jdk 7
Best Of Jdk 7Best Of Jdk 7
Best Of Jdk 7
Kaniska Mandal
 
Linux basics
Linux basicsLinux basics
Linux basics
sirmanohar
 
02 fundamentals
02 fundamentals02 fundamentals
02 fundamentals
sirmanohar
 
Chapter28 data-file-handling
Chapter28 data-file-handlingChapter28 data-file-handling
Chapter28 data-file-handling
Deepak Singh
 
errno is an integer variable, defined in errno.h, that is set by sys.pdf
errno is an integer variable, defined in errno.h, that is set by sys.pdferrno is an integer variable, defined in errno.h, that is set by sys.pdf
errno is an integer variable, defined in errno.h, that is set by sys.pdf
arjuntiwari586
 
Article link httpiveybusinessjournal.compublicationmanaging-.docx
Article link httpiveybusinessjournal.compublicationmanaging-.docxArticle link httpiveybusinessjournal.compublicationmanaging-.docx
Article link httpiveybusinessjournal.compublicationmanaging-.docx
fredharris32
 
Files in php
Files in phpFiles in php
Files in php
sana mateen
 
SAX, DOM & JDOM parsers for beginners
SAX, DOM & JDOM parsers for beginnersSAX, DOM & JDOM parsers for beginners
SAX, DOM & JDOM parsers for beginners
Hicham QAISSI
 

Similar to How to Read Excel Files in Java (1).pdf (20)

Hands On Intro to Node.js
Hands On Intro to Node.jsHands On Intro to Node.js
Hands On Intro to Node.js
 
CS101S. ThompsonUniversity of BridgeportLab 7 Files, File.docx
CS101S. ThompsonUniversity of BridgeportLab 7 Files, File.docxCS101S. ThompsonUniversity of BridgeportLab 7 Files, File.docx
CS101S. ThompsonUniversity of BridgeportLab 7 Files, File.docx
 
7 Data File Handling
7 Data File Handling7 Data File Handling
7 Data File Handling
 
Filesin c++
Filesin c++Filesin c++
Filesin c++
 
Import and Export Excel Data using openxlsx in R Studio
Import and Export Excel Data using openxlsx in R StudioImport and Export Excel Data using openxlsx in R Studio
Import and Export Excel Data using openxlsx in R Studio
 
UNIT 5.pptx
UNIT 5.pptxUNIT 5.pptx
UNIT 5.pptx
 
InstructionYou’ll probably want to import FileReader, PrintWriter,.pdf
InstructionYou’ll probably want to import FileReader, PrintWriter,.pdfInstructionYou’ll probably want to import FileReader, PrintWriter,.pdf
InstructionYou’ll probably want to import FileReader, PrintWriter,.pdf
 
APPLICATION TO DOCUMENT ALL THE DETAILS OF JAVA CLASSES OF A PROJECT AT ONCE...
APPLICATION TO DOCUMENT ALL THE  DETAILS OF JAVA CLASSES OF A PROJECT AT ONCE...APPLICATION TO DOCUMENT ALL THE  DETAILS OF JAVA CLASSES OF A PROJECT AT ONCE...
APPLICATION TO DOCUMENT ALL THE DETAILS OF JAVA CLASSES OF A PROJECT AT ONCE...
 
Class 1
Class 1Class 1
Class 1
 
Class 1
Class 1Class 1
Class 1
 
Filehandling
FilehandlingFilehandling
Filehandling
 
ELF
ELFELF
ELF
 
Best Of Jdk 7
Best Of Jdk 7Best Of Jdk 7
Best Of Jdk 7
 
Linux basics
Linux basicsLinux basics
Linux basics
 
02 fundamentals
02 fundamentals02 fundamentals
02 fundamentals
 
Chapter28 data-file-handling
Chapter28 data-file-handlingChapter28 data-file-handling
Chapter28 data-file-handling
 
errno is an integer variable, defined in errno.h, that is set by sys.pdf
errno is an integer variable, defined in errno.h, that is set by sys.pdferrno is an integer variable, defined in errno.h, that is set by sys.pdf
errno is an integer variable, defined in errno.h, that is set by sys.pdf
 
Article link httpiveybusinessjournal.compublicationmanaging-.docx
Article link httpiveybusinessjournal.compublicationmanaging-.docxArticle link httpiveybusinessjournal.compublicationmanaging-.docx
Article link httpiveybusinessjournal.compublicationmanaging-.docx
 
Files in php
Files in phpFiles in php
Files in php
 
SAX, DOM & JDOM parsers for beginners
SAX, DOM & JDOM parsers for beginnersSAX, DOM & JDOM parsers for beginners
SAX, DOM & JDOM parsers for beginners
 

More from SudhanshiBakre1

IoT Security.pdf
IoT Security.pdfIoT Security.pdf
IoT Security.pdf
SudhanshiBakre1
 
Top Java Frameworks.pdf
Top Java Frameworks.pdfTop Java Frameworks.pdf
Top Java Frameworks.pdf
SudhanshiBakre1
 
Numpy ndarrays.pdf
Numpy ndarrays.pdfNumpy ndarrays.pdf
Numpy ndarrays.pdf
SudhanshiBakre1
 
Float Data Type in C.pdf
Float Data Type in C.pdfFloat Data Type in C.pdf
Float Data Type in C.pdf
SudhanshiBakre1
 
IoT Hardware – The Backbone of Smart Devices.pdf
IoT Hardware – The Backbone of Smart Devices.pdfIoT Hardware – The Backbone of Smart Devices.pdf
IoT Hardware – The Backbone of Smart Devices.pdf
SudhanshiBakre1
 
Internet of Things – Contiki.pdf
Internet of Things – Contiki.pdfInternet of Things – Contiki.pdf
Internet of Things – Contiki.pdf
SudhanshiBakre1
 
Java abstract Keyword.pdf
Java abstract Keyword.pdfJava abstract Keyword.pdf
Java abstract Keyword.pdf
SudhanshiBakre1
 
Node.js with MySQL.pdf
Node.js with MySQL.pdfNode.js with MySQL.pdf
Node.js with MySQL.pdf
SudhanshiBakre1
 
Collections in Python - Where Data Finds Its Perfect Home.pdf
Collections in Python - Where Data Finds Its Perfect Home.pdfCollections in Python - Where Data Finds Its Perfect Home.pdf
Collections in Python - Where Data Finds Its Perfect Home.pdf
SudhanshiBakre1
 
File Handling in Java.pdf
File Handling in Java.pdfFile Handling in Java.pdf
File Handling in Java.pdf
SudhanshiBakre1
 
Types of AI you should know.pdf
Types of AI you should know.pdfTypes of AI you should know.pdf
Types of AI you should know.pdf
SudhanshiBakre1
 
Streams in Node .pdf
Streams in Node .pdfStreams in Node .pdf
Streams in Node .pdf
SudhanshiBakre1
 
Annotations in Java with Example.pdf
Annotations in Java with Example.pdfAnnotations in Java with Example.pdf
Annotations in Java with Example.pdf
SudhanshiBakre1
 
RESTful API in Node.pdf
RESTful API in Node.pdfRESTful API in Node.pdf
RESTful API in Node.pdf
SudhanshiBakre1
 
Top Cryptocurrency Exchanges of 2023.pdf
Top Cryptocurrency Exchanges of 2023.pdfTop Cryptocurrency Exchanges of 2023.pdf
Top Cryptocurrency Exchanges of 2023.pdf
SudhanshiBakre1
 
Epic Python Face-Off -Methods vs.pdf
Epic Python Face-Off -Methods vs.pdfEpic Python Face-Off -Methods vs.pdf
Epic Python Face-Off -Methods vs.pdf
SudhanshiBakre1
 
Django Tutorial_ Let’s take a deep dive into Django’s web framework.pdf
Django Tutorial_ Let’s take a deep dive into Django’s web framework.pdfDjango Tutorial_ Let’s take a deep dive into Django’s web framework.pdf
Django Tutorial_ Let’s take a deep dive into Django’s web framework.pdf
SudhanshiBakre1
 
Benefits Of IoT Salesforce.pdf
Benefits Of IoT Salesforce.pdfBenefits Of IoT Salesforce.pdf
Benefits Of IoT Salesforce.pdf
SudhanshiBakre1
 
Epic Python Face-Off -Methods vs. Functions.pdf
Epic Python Face-Off -Methods vs. Functions.pdfEpic Python Face-Off -Methods vs. Functions.pdf
Epic Python Face-Off -Methods vs. Functions.pdf
SudhanshiBakre1
 
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdfPython Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
SudhanshiBakre1
 

More from SudhanshiBakre1 (20)

IoT Security.pdf
IoT Security.pdfIoT Security.pdf
IoT Security.pdf
 
Top Java Frameworks.pdf
Top Java Frameworks.pdfTop Java Frameworks.pdf
Top Java Frameworks.pdf
 
Numpy ndarrays.pdf
Numpy ndarrays.pdfNumpy ndarrays.pdf
Numpy ndarrays.pdf
 
Float Data Type in C.pdf
Float Data Type in C.pdfFloat Data Type in C.pdf
Float Data Type in C.pdf
 
IoT Hardware – The Backbone of Smart Devices.pdf
IoT Hardware – The Backbone of Smart Devices.pdfIoT Hardware – The Backbone of Smart Devices.pdf
IoT Hardware – The Backbone of Smart Devices.pdf
 
Internet of Things – Contiki.pdf
Internet of Things – Contiki.pdfInternet of Things – Contiki.pdf
Internet of Things – Contiki.pdf
 
Java abstract Keyword.pdf
Java abstract Keyword.pdfJava abstract Keyword.pdf
Java abstract Keyword.pdf
 
Node.js with MySQL.pdf
Node.js with MySQL.pdfNode.js with MySQL.pdf
Node.js with MySQL.pdf
 
Collections in Python - Where Data Finds Its Perfect Home.pdf
Collections in Python - Where Data Finds Its Perfect Home.pdfCollections in Python - Where Data Finds Its Perfect Home.pdf
Collections in Python - Where Data Finds Its Perfect Home.pdf
 
File Handling in Java.pdf
File Handling in Java.pdfFile Handling in Java.pdf
File Handling in Java.pdf
 
Types of AI you should know.pdf
Types of AI you should know.pdfTypes of AI you should know.pdf
Types of AI you should know.pdf
 
Streams in Node .pdf
Streams in Node .pdfStreams in Node .pdf
Streams in Node .pdf
 
Annotations in Java with Example.pdf
Annotations in Java with Example.pdfAnnotations in Java with Example.pdf
Annotations in Java with Example.pdf
 
RESTful API in Node.pdf
RESTful API in Node.pdfRESTful API in Node.pdf
RESTful API in Node.pdf
 
Top Cryptocurrency Exchanges of 2023.pdf
Top Cryptocurrency Exchanges of 2023.pdfTop Cryptocurrency Exchanges of 2023.pdf
Top Cryptocurrency Exchanges of 2023.pdf
 
Epic Python Face-Off -Methods vs.pdf
Epic Python Face-Off -Methods vs.pdfEpic Python Face-Off -Methods vs.pdf
Epic Python Face-Off -Methods vs.pdf
 
Django Tutorial_ Let’s take a deep dive into Django’s web framework.pdf
Django Tutorial_ Let’s take a deep dive into Django’s web framework.pdfDjango Tutorial_ Let’s take a deep dive into Django’s web framework.pdf
Django Tutorial_ Let’s take a deep dive into Django’s web framework.pdf
 
Benefits Of IoT Salesforce.pdf
Benefits Of IoT Salesforce.pdfBenefits Of IoT Salesforce.pdf
Benefits Of IoT Salesforce.pdf
 
Epic Python Face-Off -Methods vs. Functions.pdf
Epic Python Face-Off -Methods vs. Functions.pdfEpic Python Face-Off -Methods vs. Functions.pdf
Epic Python Face-Off -Methods vs. Functions.pdf
 
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdfPython Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
 

Recently uploaded

Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
Jeffrey Haguewood
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
Zilliz
 
Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
Zilliz
 
Trusted Execution Environment for Decentralized Process Mining
Trusted Execution Environment for Decentralized Process MiningTrusted Execution Environment for Decentralized Process Mining
Trusted Execution Environment for Decentralized Process Mining
LucaBarbaro3
 
Digital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying AheadDigital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying Ahead
Wask
 
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
Edge AI and Vision Alliance
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
Ivanti
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
panagenda
 
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfHow to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
Chart Kalyan
 
Skybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoptionSkybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoption
Tatiana Kojar
 
Taking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdfTaking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdf
ssuserfac0301
 
Best 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERPBest 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERP
Pixlogix Infotech
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
panagenda
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
innovationoecd
 
Digital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
Digital Banking in the Cloud: How Citizens Bank Unlocked Their MainframeDigital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
Digital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
Precisely
 
Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |
AstuteBusiness
 
A Comprehensive Guide to DeFi Development Services in 2024
A Comprehensive Guide to DeFi Development Services in 2024A Comprehensive Guide to DeFi Development Services in 2024
A Comprehensive Guide to DeFi Development Services in 2024
Intelisync
 
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-EfficiencyFreshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
ScyllaDB
 
Choosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptxChoosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptx
Brandon Minnick, MBA
 

Recently uploaded (20)

Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
 
Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
 
Trusted Execution Environment for Decentralized Process Mining
Trusted Execution Environment for Decentralized Process MiningTrusted Execution Environment for Decentralized Process Mining
Trusted Execution Environment for Decentralized Process Mining
 
Digital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying AheadDigital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying Ahead
 
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
 
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfHow to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
 
Skybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoptionSkybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoption
 
Taking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdfTaking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdf
 
Best 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERPBest 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERP
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
 
Digital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
Digital Banking in the Cloud: How Citizens Bank Unlocked Their MainframeDigital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
Digital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
 
Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |
 
A Comprehensive Guide to DeFi Development Services in 2024
A Comprehensive Guide to DeFi Development Services in 2024A Comprehensive Guide to DeFi Development Services in 2024
A Comprehensive Guide to DeFi Development Services in 2024
 
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-EfficiencyFreshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
 
Choosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptxChoosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptx
 

How to Read Excel Files in Java (1).pdf

  • 1. How to Read Excel Files in Java? In today’s computer world, excel files are an integral part of every business ranging from small to large. The uses of Excel files include data management, analysis, charting, graphing, etc. So when we come to the programming side, there will be a situation where we have to handle Excel files. In Java programming, there is no built-in feature to support Excel files. Yet we can handle Excel files easily by using the third-party API named Apache POI. In today’s article, we will look at how to read Excel files in Java using the Apache POI API. Excel files: We all know that Excel files are spreadsheets that make data handling and manipulation easier. Generally, there are two file formats available for Excel files. They are 1. .xls 2. .xlsx. The xls format is the older one for 2003 and older versions. And xlsx is a new format for excel 2007 and later. Apache POI:
  • 2. Generally, Apache POI (Poor Obfuscation Implementation) is an open-source library for handling Microsoft office related files. Java does not have the built-in feature to handle excel files. So, We use Apache POI, a third-party Java API with classes and interfaces to deal with reading and writing operations in excel files. This API supports both .xls and .xlsx formats. To deal with the .xls format, we use HSSF(Horrible SpreadSheet Format) implementation. And to deal with the .xlsx format, we use XSSF(XML SpreadSheet Format) implementation. Classes: We all know that Excel files consist of Workbook, WorkSheets, cells, rows, and columns. The API comprises a variety of classes to incorporate the functionality that deals with excel files. There are separate classes available to deal with .xls and .xlsx formats. HSSFWorkbook, HSSFSheet, HSSFRow, and HSSFCell are the classes that provide the functionality for handling workbooks, sheets, rows, and cells in xls format files, respectively. Similarly, the XSSFWorkbook, XSSFSheet, XSSFRow, and XSSFCell are the classes that provide the functionality for handling workbooks, sheets, rows, and cells in xlsx format files, respectively. Interface: This API provides some common interfaces for all the classes discussed above. They are:
  • 3. 1. Workbook – Workbook is a common interface implemented by both HSSFWorkbook and XSSFWorkbook classes. 2. Sheet – The HSSFSheet and XSSFSheet classes implement this interface. 3. Row – Both HSSFRow and XSSFRow classes use this interface. 4. Cell – The HSSFCell and XSSFCell classes implement this interface. Prerequisites for using ApachePOI to read excel file in java: The requirements for using ApachePOI are: 1. An eclipse IDE 2. poi-bin-5.2.3-20220909.zip folder Extract the zip file. There is a list of jar files required to use ApachePOI. You can download the latest versions of the jar if needed. 3. An excel file in both formats. a. In this article, we will use the excel files named FirstCode.xls and FirstCode.xlsx. b. The content of the files are: Now follow the steps given below to set up the environment. 1. Open the Eclipse IDE 2. Create a new java project.
  • 4. 3. Add all the downloaded jar files in the classpath, as shown below. Right-click the project name→ Build Path → Configure Build Path → Click the libraries tab → Add External jars in Classpath → Select all the jars discussed above → Click Apply and close. If you are using maven, you should include the following dependencies in your pom.xml file. <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>5.2.0</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>5.2.0</version> </dependency> Code to read the xls file in java: import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.Scanner; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  • 5. import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.FormulaEvaluator; import org.apache.poi.ss.usermodel.Row; public class ReadExcelFile { public static void main(String args[]) { try { //Creating a file object and getting the excel file. File file= new File("E:FirstCode.xls"); // Creating FileInputStream object to read the file. FileInputStream fisObject=new FileInputStream(file); //Creating Workbook instance for .xls file. HSSFWorkbook workbook=new HSSFWorkbook(fisObject); //Getting the sheet number from the user. System.out.println("Enter the sheet number:"); Scanner scan = new Scanner(System.in); int sheetnumber = scan.nextInt(); //Creating a Sheet object to get the required sheet in the file. HSSFSheet sheet=workbook.getSheetAt(sheetnumber); //Evaluating cell type FormulaEvaluator formulaEvaluator=workbook.getCreationHelper().createFormulaEvaluator(); //Iterating the rows with, for each loop.
  • 6. for(Row row: sheet) { //Iterating the cells with, for each loop. for(Cell cell: row) { switch(formulaEvaluator.evaluateInCell(cell).getCellType()) { //Numeric cell type. case NUMERIC: //Getting the cell value as a number and printing it. System.out.print(cell.getNumericCellValue()+ "tt"); break; //String cell type. case STRING: //Getting the cell value as a string and printing it. System.out.print(cell.getStringCellValue()+ "tt"); break; default: break; } } System.out.println(); }
  • 7. workbook.close(); } catch(FileNotFoundException exception) { //If there is no excel file with the given name found in the specified location, it throws FileNotFoundException. System.out.println("File Not Found."); } catch(IllegalArgumentException exception) { //If the sheet is empty, it throws an IllegalArgumentException. System.out.println("Sheet is empty"); } catch(Exception exception) { //To deal with other Exceptions. exception.printStackTrace(); } } } Output: ■ When the excel file reading is successful, whole file will be displayed as output. ■ When there is no excel file with the given name found in the specified location, the output will be: File Not Found ■ When there is no data in the given sheet index, the output will be:
  • 8. Sheet is empty Code to read the xlsx file in java: import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.Iterator; import java.util.Scanner; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class ReadExcelFile { public static void main(String[] args) { try { //Creating a file object and getting the excel file. File file = new File("E:FirstCode.xlsx"); // Creating FileInputStream object to read the file. FileInputStream fisObject = new FileInputStream(file); //Creating Workbook instance for .xlsx file.
  • 9. XSSFWorkbook workbook = new XSSFWorkbook(fisObject); //Getting the sheet number from the user. System.out.println("Enter the sheet number:"); Scanner scan = new Scanner(System.in); int sheetnumber = scan.nextInt(); //Creating a Sheet object to get the required sheet in the file. XSSFSheet sheet = workbook.getSheetAt(sheetnumber); //Using an iterator to iterate the sheet object to get rows. Iterator<Row> itr = sheet.iterator(); while (itr.hasNext()) { // Getting the row values. Row row = itr.next(); //Iterating each column in the row. Iterator<Cell> cellIterator = row.cellIterator(); while (cellIterator.hasNext()) { //Getting column values. Cell cell = cellIterator.next(); //Getting cell type. switch (cell.getCellType()) { //String cell type.
  • 10. case STRING: //Getting the cell value as a string and printing it. System.out.print(cell.getStringCellValue() + "ttt"); break; //Numeric cell type. case NUMERIC: //Getting the cell value as a number and printing it. System.out.print(cell.getNumericCellValue() + "ttt"); break; default: break; } } System.out.println(""); } workbook.close(); } catch(FileNotFoundException exception) { //If there is no excel file with the given name found in the specified location, it throws FileNotFoundException. System.out.println("File Not Found."); }
  • 11. catch(IllegalArgumentException exception) { //If the sheet is empty, it throws an IllegalArgumentException. System.out.println("Sheet is empty"); } catch(Exception exception) { //To deal with other Exceptions. exception.printStackTrace(); } } } Output: ■ When the excel file reading is successful, the output will be the whole file. ■ When there is no excel file with the given name found in the specified location, the output will be: File Not Found ■ When there is no data in the given sheet index, the output will be: Sheet is Empty Code to read a particular cell value in the xlsx file in Java: import java.io.FileInputStream;
  • 12. import java.io.FileNotFoundException; import java.io.IOException; import java.util.Scanner; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class ReadExcelFile { public static void main(String[] args) { //Creating an object for the ReadExcelFile class. ReadExcelFile rc=new ReadExcelFile(); System.out.println("Enter the sheet, row, and column number of the cell:"); //Getting the input for sheet, row, and column number, from the user. Scanner scan = new Scanner(System.in); int sheetnumber = scan.nextInt(); int row = scan.nextInt(); int column = scan.nextInt(); //ReadCellData function call String vOutput=rc.ReadCellData(row, column, sheetnumber); //Checking whether the return value is null. The method returns null when the sheet or cell is empty.
  • 13. if(vOutput!=null) //Printing the cell value. System.out.println(vOutput); } //Method for getting the cell value. public String ReadCellData(int vRow, int vColumn, int vsheet) { //Variable to store the cell value. String value=null; //Initializing Workbook object as null. Workbook workbook=null; try { // Creating FileInputStream object to read the file. FileInputStream fis=new FileInputStream("E:FirstCode.xlsx"); //Creating Workbook instance for .xls file. workbook=new XSSFWorkbook(fis); //Creating a Sheet object to get the required sheet in the file. Sheet sheet=workbook.getSheetAt(vsheet); // Getting the specified row. Row row=sheet.getRow(vRow); // Getting the specified column. Cell cell=row.getCell(vColumn);
  • 14. // Getting the specified cell value. value=cell.getStringCellValue(); } catch(FileNotFoundException exception) { //If there is no excel file with the given name found in the specified location, it throws FileNotFoundException. System.out.println("File Not Found."); } catch(IOException exception) { System.out.println("Invalid inputs."); } catch(NullPointerException exception) { //If the cell is empty, it throws a NullPointerException. System.out.println("No data in the specified cell"); } catch(IllegalArgumentException exception) { //If the sheet is empty, it throws an IllegalArgumentException. System.out.println("Empty sheet"); }
  • 15. catch(Exception exception) { //To deal with other Exceptions. exception.printStackTrace(); } // Returns the corresponding cell value. return value; } } Output: ■ When the excel file reading is successful, the output will be the desired value. ■ When there is no excel file with the given name found in the specified location, the output will be: File Not Found ■ When there is no data in the given sheet index, the output will be: Empty Sheet ■ When there is no data in the given cell, the output will be: No data in the specified cell Code to read xls and xlsx files in java: import java.io.File; import java.io.FileNotFoundException;
  • 16. import java.util.Scanner; import org.apache.poi.ss.usermodel.DataFormatter; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.WorkbookFactory; public class ReadExcelFile { public static final String FILE_PATH = "E:FirstCode.xlsx"; public static void main(String[] args) { try { //Creating Workbook instance for excel file for both format .xls and .xlsx file. Workbook workbook = WorkbookFactory.create(new File(FILE_PATH)); // Getting the number of sheets in the Workbook. System.out.println("Workbook consists of " + workbook.getNumberOfSheets() + " Sheets : "); System.out.println("Enter the sheet index number:"); //Getting the sheet number from the user. Scanner scan = new Scanner(System.in); int sheetnumber = scan.nextInt(); //Creating a Sheet object to get the required sheet in the file. Sheet sheet = workbook.getSheetAt(sheetnumber); // Create a DataFormatter to format each cell value as String. DataFormatter dataFormatter = new DataFormatter(); //Using forEach loop with lambda(Java8).
  • 17. sheet.forEach(row -> { row.forEach(cell -> { String cellValue = dataFormatter.formatCellValue(cell); System.out.print(cellValue + "tt"); }); System.out.println(); }); // Closing the workbook object. workbook.close(); } catch(FileNotFoundException exception) { //If there is no excel file with the given name found in the specified location, it throws FileNotFoundException. System.out.println("File Not Found."); } catch(IllegalArgumentException exception) { //If the sheet is empty, it throws an IllegalArgumentException. System.out.println("Sheet is empty"); } catch(Exception exception) {
  • 18. //To deal with other Exceptions. exception.printStackTrace(); } } } Output: ■ When the excel file reading is successful, the output will be as desired. ■ When there is no Excel file with the given name found in the specified location, the output will be: File not Found ■ When there is no data in the given sheet index, the output will be: Sheet is Empty Additional tips: If your excel file has more than one sheet, you can get the number of sheets and iterate over them. Refer to the code snippet for a better understanding. Code snippet: workbook.forEach(sheet -> { System.out.println("=> " + sheet.getSheetName()); }); To iterate among the sheets or rows, or cells, you can use one of the following ways: 1. for each loop with a lambda expression.
  • 19. 2. for each loop 3. Iterator I demonstrated each iterating way in the sample codes above for your reference. Summary There is another API for handling excel files named JXL or JEXCEL. But this API supports only xls files and does not support xlsx files. Its last update was in 2009. So everyone uses ApachePOI now. I hope you understand how to use ApachePOI to read excel files in java. Thank you for reading.