Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
85 views

TCB - Reading Excel File Using Java Code

1. The document describes how to read data from an Excel file using Java code with the Apache POI library. 2. It provides sample code that defines an Excel file path, opens the file as a workbook, gets the first sheet, and then iterates through rows and cells to print out cell values. 3. The code handles both older .xls files and newer .xlsx files by determining the workbook type and using either HSSFWorkbook or XSSFWorkbook accordingly.

Uploaded by

namit
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
85 views

TCB - Reading Excel File Using Java Code

1. The document describes how to read data from an Excel file using Java code with the Apache POI library. 2. It provides sample code that defines an Excel file path, opens the file as a workbook, gets the first sheet, and then iterates through rows and cells to print out cell values. 3. The code handles both older .xls files and newer .xlsx files by determining the workbook type and using either HSSFWorkbook or XSSFWorkbook accordingly.

Uploaded by

namit
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

More vats.namit@gmail.

com

TCB
Reading Excel file using java code thecodebu

How to use JAVA code to read the excel cells?

Here it goes -

Full code is available @ https://github.com/namitsharma99/fileHandlingUsingJava

With reference to com.java.code.ReadExcel.java, the following tasks are handled.

1. Let your excel's path be defined with variable - myExcelPath TCB


2. Invoke excelReader() method.
3. Get to know your workbook type based on excel version i.e. HSSFWorkbook or XSSFWorkbook. We are taking XSSFWorkbook for this
example.
About Me
4. Follow the comments section and BOOM, it's done.
thecode
package com.java.code;
View my co
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Iterator;
FB Page
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ReadExcel { Find me o
public static void main(String[] args) {

String myExcelPath = "sampleExcel.xlsx";


excelReader(myExcelPath);

} Get code o
private static void excelReader(String myExcelPath) {
XSSFWorkbook myWorkbook = null; Follow
try {
// Create an input stream for your file
FileInputStream myIpStream = new FileInputStream(myExcelPath);

// Initiate your excel workbook html-css-b


// for older .xls-binary files try below (HSSFWorkbook)
// HSSFWorkbook myWorkbook = new HSSFWorkbook(myIpStream);
/* make sure your all poi jars have same version else you would get an exception while parsing -
Exception in thread "main" java.lang.IllegalAccessError: tried to
access method
org.apache.poi.util.POILogger.log(ILjava/lang/Object;)V from
class org.apache.poi.openxml4j.opc.PackageRelationshipCollection */
// Access the workbook
myWorkbook = new XSSFWorkbook(myIpStream);
Exam 48
// Initiate the worksheet
XSSFSheet myWorkSheet = myWorkbook.getSheet("Sheet1"); Issuer: M
Provided
/* A generally used method is giving me deprecate warning for getCellTypeEnum(), so I thought of travelling Acclaim
the other road.
-> Iterator<Row> myItr = myWorkSheet.iterator();
while (myItr.hasNext()) {
Cell cell = (Cell) myItr.next();
if (cell.getCellTypeEnum() == CellType.STRING) {
System.out.println(cell.getStringCellValue());
}
}
*/

/* Hence I am using the below technique. Also, the cell and row types will change as
per XSSF or HSSF, whichever type you are using based on excel sheets. Contact fo
*/
// fetch all rows of a worksheet, using iterator
Iterator<Row> xssfRowItr = myWorkSheet.rowIterator(); Name
while (xssfRowItr.hasNext()) {
XSSFRow xssfRow = (XSSFRow) xssfRowItr.next();
// fetch all cells of a row, using iterator
Iterator<Cell> xssfCellItr = xssfRow.cellIterator();
while (xssfCellItr.hasNext()) {
Cell myCell = xssfCellItr.next();
// fetch the content of each cell Email *
System.out.print(myCell.getStringCellValue() + " ");
}
System.out.println(" ");
}
Message *
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (null != myWorkbook)
myWorkbook.close();
} catch (Exception e) { Send
System.out.println(e);
}
}
}

Output -
Cell 0,0  Cell 0,1  Cell 0,2    Blog archi
Cell 1,0  Cell 1,1  Cell 1,2   
Cell 2,0  Cell 2,1  Cell 2,2 
► 2020 (6

Happy Coding... ► 2018 (7


▼ 2017 (3
► Nove
at March 23, 2017
► Octo
Labels: apache poi, excel, Java
► July
► June
No comments:
► May
Post a comment ► April
▼ Marc

Enter your comment... STRU


IMA
DO
SERV
DA
Comment as: thecodebuddy ( Sign out UP
DO
Epic
Publish Preview Notify me one
com
Write
jav
Writin
Newer Post Home Older Post jav
JAVA
Subscribe to: Post Comments (Atom) -A
FO

Featured post JAVA


-T
&D
How to take backup of MYSQL tables daily and remove the older backups
JAVA
In day to day heavy transactions happening in our DB, we sometimes wish to retain the previous states of the tables. This not only prevents ... -H
JAVA
-S
JAVA
-R
SIM
Dream
Mesm
Read
jav
Read
jav
Binar
Imp
Jav
Linea
Imp
Jav
White
Un
ECST
MAG
WSO
Pa
Me
JAVA
can
usi
Javas
Ma
Op
REST
pin
Hib

► Febr

► 2016 (3

WSO2 ESB - How to use PayloadFactory Mediator


How to use PayloadFactory Mediator As per the WSO2-ESB documentation of PayloadFactory Mediator, it is stated that this me...

Reading Excel file using java code


How to use JAVA code to read the excel cells? Here it goes - Full code is available @ https://github.com/namitsharma99/fileHandlingUs...

JAVASCRIPT SAMPLES - TIC TAC TOE GAME & DYNAMIC TABLE CREATION IN JSP
Hello Buddies. It's time to play tic-tac-toe, but this time, not with pen and paper. We will create our own page that allows us to ...

Total Page

Popular Po
Mediator A
documenta
Mediator, it

Reading Ex
How to use
excel cells?
available @
harma99/fi

Hello Budd
toe, but this
paper. We
that allows

custom cla
on to cover

using mous
Complete c
https:/...

code writte
very basic
complete c

time. A com
developers

recently, an
developers
banging. A
w...

JAVA code
comparison
Hello Budd
useful piec
you in hand
comparison

O(n^2) vs O
the max co
numerical S
Hello Budd
question re
so thought
Given a str
Search Th

Blog archi

► 2020 (6
► 2018 (7
▼ 2017 (3
► Nove
► Octo
► July
► June
► May
► April
▼ Marc
STRU
IMA
DO
SERV
DA
UP
DO
Epic
one
com
Write
jav
Writin
jav
JAVA
-A
FO
JAVA
-T
&D
JAVA
-H
JAVA
-S
JAVA
-R
SIM
Dream
Mesm
Read
jav
Read
jav
Binar
Imp
Jav
Linea
Imp
Jav
White
Un
ECST
MAG
WSO
Pa
Me
JAVA
can
usi
Javas
Ma
Op
REST
pin
Hib

► Febr

► 2016 (3

Newsletter

Email addr
Ads

Head First
A...
INR 870.0

Shop n
Labels

AJAX algo Amazon Web Services Android Angular 2 Angular Components Apache httpd apache poi API API GATEWAY APK Automate build AWS AWS and Gmail AWS Email AWS Lambda AWS Lambda No
SES backup binary search binary tree Bootstrap browser issue BST chat Cheat sheet chrome class mediator cloning code code-snippet Complexity Analysis concurrency consumer core java css CSV cu
structures Data Structures and Algorithms database management deep download DSA DTMF eclipse EDM Electronic Digital Music electronic music Electronics Enum epic violins ESB esb5 event

fedora file firefox foreach mediator game games Git Git Hub Git Lab Git Repo Go Go Tutorials GoLang hello world Hibernate hip hop html HTTP GET POST PUT DELETE J2EE Java JAVA.
Jenkins jquery jQuery in Angular 2 JS JSP kafka KEYGEN LAMBDA linear search mediation messaging microservices mozilla MSTSC multi threading MySQL NG-2 NODEJS NPM Path Annotations Payload
PUTTY quick reference read text file read write csv remote access REST S3 schedulers sequence Server shallow shooting game small programs snake game socket programming Speech to Text springboot S
questions tables text file writer thecodebuddy tic-tac-toe game time complexity topic Trance TUNNEL unix upload version-check white paper WINDOWS Workbench WSO2 WSO2 ESB XML JSON transformation

Awesome Inc. theme. Powered by Blogger.

You might also like