SlideShare uma empresa Scribd logo
1 de 13
Apache POI Tutorial
Apache POI is a popular API that allows programmers to create, modify, and
display MS Office files using Java programs. It is an open source library
developed and distributed by Apache Software Foundation to design or modify
Microsoft Office files using Java program. The name POI was originally an
acronym for Poor Obfuscation Implementation, referring humorously to the
fact that the file formats seemed to be deliberately obfuscated, but poorly, since
they were successfully reverse-engineered.
• HSSF (Horrible SpreadSheet Format) – reads and writes Microsoft Excel (XLS)
format files.
• XSSF (XML SpreadSheet Format) – reads and writes Office Open XML (XLSX) format
files.
• HPSF (Horrible Property Set Format) – reads “Document Summary” information
from Microsoft Office files.
• HWPF (Horrible Word Processor Format) – aims to read and write Microsoft Word
97 (DOC) format files.
• HSLF (Horrible Slide Layout Format) – a pure Java implementation for Microsoft
PowerPoint files.
• HDGF (Horrible DiaGram Format) – an initial pure Java implementation for
Microsoft Visio binary files.
• HPBF (Horrible PuBlisher Format) – a pure Java implementation for Microsoft
Publisher files.
• HSMF (Horrible Stupid Mail Format) – a pure Java implementation for Microsoft
Outlook MSG files
• DDF (Dreadful Drawing Format) – a package for decoding the Microsoft Office
Drawing format.
• Working with .xlsx files
• The classes we used in above code
snippet, HSSFWorkbook and HSSFSheet works for .xls format. In
order to work with newer xls format viz .xlsx, you need to see
newer POI classes like:
• import org.apache.poi.hssf.usermodel.HSSFSheet; import
org.apache.poi.xssf.usermodel.XSSFSheet; //.. FileInputStream file =
new FileInputStream(new File("C:test.xlsx")); //Get the workbook
instance for XLS file XSSFWorkbook workbook = new XSSFWorkbook
(file); //Get first sheet from the workbook XSSFSheet sheet =
workbook.getSheetAt(0); //Get iterator to all the rows in current
sheet Iterator<Row> rowIterator = sheet.iterator(); //Get iterator to
all cells of current row Iterator<Cell> cellIterator = row.cellIterator();
Create Blank Workbook
• The following simple program is used to create a blank Microsoft
Excel Workbook.
• import java.io.*; import org.apache.poi.xssf.usermodel.*;
• public class CreateWorkBook {
• public static void main(String[] args)throws Exception {
• //Create Blank workbook
• XSSFWorkbook workbook = new XSSFWorkbook(); //Create file
system using specific name
• FileOutputStream out = new FileOutputStream( new
File("createworkbook.xlsx"));
• //write operation workbook using file out object
workbook.write(out); out.close(); System.out.println("
createworkbook.xlsx written successfully");
• } }
Open Existing Workbook
• Use the following code to open an existing workbook.
• import java.io.*; import org.apache.poi.xssf.usermodel.*;
• public class OpenWorkBook {
• public static void main(String args[])throws Exception { File file =
new File("openworkbook.xlsx"); FileInputStream fIP = new
FileInputStream(file);
• //Get the workbook instance for XLSX file
• XSSFWorkbook workbook = new XSSFWorkbook(fIP); if(file.isFile()
&& file.exists())
• { System.out.println( "openworkbook.xlsx file open successfully.");
• } else { System.out.println( "Error to open openworkbook.xlsx file.");
}
}
}
We will read above xls file using
Apache POI and prints the data.
• Consider a sample excel file:
• test.xls
• try {
•
• FileInputStream file = new FileInputStream(new File("C:test.xls"));
•
• //Get the workbook instance for XLS file
• HSSFWorkbook workbook = new HSSFWorkbook(file);
• //Get first sheet from the workbook
• HSSFSheet sheet = workbook.getSheetAt(0);
•
• //Iterate through each rows from first sheet
• Iterator<Row> rowIterator = sheet.iterator();
• while(rowIterator.hasNext()) {
• Row row = rowIterator.next();
•
• //For each row, iterate through each columns
• Iterator<Cell> cellIterator = row.cellIterator();
• while(cellIterator.hasNext()) {
•
• Cell cell = cellIterator.next();
• switch(cell.getCellType()) {
• case Cell.CELL_TYPE_BOOLEAN:
•
System.out.print(cell.getBooleanCellValue() + "tt");
• break;
• case Cell.CELL_TYPE_NUMERIC:
•
System.out.print(cell.getNumericCellValue() + "tt");
• break;
• case Cell.CELL_TYPE_STRING:
•
System.out.print(cell.getStringCellValue() + "tt");
• break;
• }
• }
• System.out.println("");
• }
• file.close();
• FileOutputStream out =
• new FileOutputStream(new
File("C:test.xls"));
• workbook.write(out);
• out.close();
•
• } catch (FileNotFoundException e) {
• e.printStackTrace();
• } catch (IOException e) {
• e.printStackTrace();
• }
• 3. Create New Excel File
• Let us create a new excel file and write data in it. Following is the API which we will
use for this purpose.
• import org.apache.poi.hssf.usermodel.HSSFSheet;
• import org.apache.poi.hssf.usermodel.HSSFWorkbook;
• //..
• HSSFWorkbook workbook = new HSSFWorkbook();
• HSSFSheet sheet = workbook.createSheet("Sample sheet");
• //Create a new row in current sheet
• Row row = sheet.createRow(0);
• //Create a new cell in current row
• Cell cell = row.createCell(0);
• //Set value to new value
• cell.setCellValue("Blahblah");
• Below is the complete code that writes a new excel with dummy data:
• HSSFWorkbook workbook = new HSSFWorkbook();
• HSSFSheet sheet = workbook.createSheet("Sample sheet");
•
• Map<String, Object[]> data = new HashMap<String, Object[]>();
• data.put("1", new Object[] {"Emp No.", "Name", "Salary"});
• data.put("2", new Object[] {1d, "John", 1500000d});
• data.put("3", new Object[] {2d, "Sam", 800000d});
• data.put("4", new Object[] {3d, "Dean", 700000d});
•
• Set<String> keyset = data.keySet();
• int rownum = 0;
• for (String key : keyset) {
• Row row = sheet.createRow(rownum++);
• Object [] objArr = data.get(key);
• int cellnum = 0;
• for (Object obj : objArr) {
• Cell cell = row.createCell(cellnum++);
• if(obj instanceof Date)
• cell.setCellValue((Date)obj);
• else if(obj instanceof Boolean)
• cell.setCellValue((Boolean)obj);
• else if(obj instanceof String)
• cell.setCellValue((String)obj);
• else if(obj instanceof Double)
• cell.setCellValue((Double)obj);
• }
• }
•
• try {
• FileOutputStream out =
• new FileOutputStream(new
File("C:new.xls"));
• workbook.write(out);
• out.close();
• System.out.println("Excel written successfully..");
•
• } catch (FileNotFoundException e) {
• e.printStackTrace();
• } catch (IOException e) {
• e.printStackTrace();
• }
Output: new.xls

Mais conteúdo relacionado

Mais procurados

Introduction to Solr
Introduction to SolrIntroduction to Solr
Introduction to SolrErik Hatcher
 
WordPress Themes 101 - dotEduGuru Summit 2013
WordPress Themes 101 - dotEduGuru Summit 2013WordPress Themes 101 - dotEduGuru Summit 2013
WordPress Themes 101 - dotEduGuru Summit 2013Curtiss Grymala
 
WordPress Themes 101 - HighEdWeb New England 2013
WordPress Themes 101 - HighEdWeb New England 2013WordPress Themes 101 - HighEdWeb New England 2013
WordPress Themes 101 - HighEdWeb New England 2013Curtiss Grymala
 
Solr: 4 big features
Solr: 4 big featuresSolr: 4 big features
Solr: 4 big featuresDavid Smiley
 
Rebuilding Solr 6 examples - layer by layer (LuceneSolrRevolution 2016)
Rebuilding Solr 6 examples - layer by layer (LuceneSolrRevolution 2016)Rebuilding Solr 6 examples - layer by layer (LuceneSolrRevolution 2016)
Rebuilding Solr 6 examples - layer by layer (LuceneSolrRevolution 2016)Alexandre Rafalovitch
 
Elastic search apache_solr
Elastic search apache_solrElastic search apache_solr
Elastic search apache_solrmacrochen
 
Intro to Apache Solr for Drupal
Intro to Apache Solr for DrupalIntro to Apache Solr for Drupal
Intro to Apache Solr for DrupalChris Caple
 
Solr Recipes Workshop
Solr Recipes WorkshopSolr Recipes Workshop
Solr Recipes WorkshopErik Hatcher
 
Gizzard, DAL and more
Gizzard, DAL and moreGizzard, DAL and more
Gizzard, DAL and morefulin tang
 
phpXperts seminar 2010 CodeMan! with noSQL!
phpXperts seminar 2010 CodeMan! with noSQL!phpXperts seminar 2010 CodeMan! with noSQL!
phpXperts seminar 2010 CodeMan! with noSQL!nhm taveer hossain khan
 
Solr Black Belt Pre-conference
Solr Black Belt Pre-conferenceSolr Black Belt Pre-conference
Solr Black Belt Pre-conferenceErik Hatcher
 
Modern, Scalable, Ambitious apps with Ember.js
Modern, Scalable, Ambitious apps with Ember.jsModern, Scalable, Ambitious apps with Ember.js
Modern, Scalable, Ambitious apps with Ember.jsMike North
 
Apache Solr-Webinar
Apache Solr-WebinarApache Solr-Webinar
Apache Solr-WebinarEdureka!
 
Rapid Prototyping with Solr
Rapid Prototyping with SolrRapid Prototyping with Solr
Rapid Prototyping with SolrErik Hatcher
 
Introduction to Apache solr
Introduction to Apache solrIntroduction to Apache solr
Introduction to Apache solrKnoldus Inc.
 
JSON REST API for WordPress
JSON REST API for WordPressJSON REST API for WordPress
JSON REST API for WordPressTaylor Lovett
 

Mais procurados (20)

Introduction to Solr
Introduction to SolrIntroduction to Solr
Introduction to Solr
 
&lt;?php + WordPress
&lt;?php + WordPress&lt;?php + WordPress
&lt;?php + WordPress
 
WordPress Themes 101 - dotEduGuru Summit 2013
WordPress Themes 101 - dotEduGuru Summit 2013WordPress Themes 101 - dotEduGuru Summit 2013
WordPress Themes 101 - dotEduGuru Summit 2013
 
WordPress Themes 101 - HighEdWeb New England 2013
WordPress Themes 101 - HighEdWeb New England 2013WordPress Themes 101 - HighEdWeb New England 2013
WordPress Themes 101 - HighEdWeb New England 2013
 
Solr: 4 big features
Solr: 4 big featuresSolr: 4 big features
Solr: 4 big features
 
Solr Masterclass Bangkok, June 2014
Solr Masterclass Bangkok, June 2014Solr Masterclass Bangkok, June 2014
Solr Masterclass Bangkok, June 2014
 
Rebuilding Solr 6 examples - layer by layer (LuceneSolrRevolution 2016)
Rebuilding Solr 6 examples - layer by layer (LuceneSolrRevolution 2016)Rebuilding Solr 6 examples - layer by layer (LuceneSolrRevolution 2016)
Rebuilding Solr 6 examples - layer by layer (LuceneSolrRevolution 2016)
 
Elastic search apache_solr
Elastic search apache_solrElastic search apache_solr
Elastic search apache_solr
 
Intro to Apache Solr for Drupal
Intro to Apache Solr for DrupalIntro to Apache Solr for Drupal
Intro to Apache Solr for Drupal
 
Solr Recipes Workshop
Solr Recipes WorkshopSolr Recipes Workshop
Solr Recipes Workshop
 
Gizzard, DAL and more
Gizzard, DAL and moreGizzard, DAL and more
Gizzard, DAL and more
 
phpXperts seminar 2010 CodeMan! with noSQL!
phpXperts seminar 2010 CodeMan! with noSQL!phpXperts seminar 2010 CodeMan! with noSQL!
phpXperts seminar 2010 CodeMan! with noSQL!
 
Solr Black Belt Pre-conference
Solr Black Belt Pre-conferenceSolr Black Belt Pre-conference
Solr Black Belt Pre-conference
 
Relate
RelateRelate
Relate
 
Modern, Scalable, Ambitious apps with Ember.js
Modern, Scalable, Ambitious apps with Ember.jsModern, Scalable, Ambitious apps with Ember.js
Modern, Scalable, Ambitious apps with Ember.js
 
Apache Solr-Webinar
Apache Solr-WebinarApache Solr-Webinar
Apache Solr-Webinar
 
JSON in Solr: from top to bottom
JSON in Solr: from top to bottomJSON in Solr: from top to bottom
JSON in Solr: from top to bottom
 
Rapid Prototyping with Solr
Rapid Prototyping with SolrRapid Prototyping with Solr
Rapid Prototyping with Solr
 
Introduction to Apache solr
Introduction to Apache solrIntroduction to Apache solr
Introduction to Apache solr
 
JSON REST API for WordPress
JSON REST API for WordPressJSON REST API for WordPress
JSON REST API for WordPress
 

Semelhante a Apache poi tutorial

How to Read Excel Files in Java (1).pdf
How to Read Excel Files in Java (1).pdfHow to Read Excel Files in Java (1).pdf
How to Read Excel Files in Java (1).pdfSudhanshiBakre1
 
Exploiting JXL using Selenium
Exploiting JXL using SeleniumExploiting JXL using Selenium
Exploiting JXL using SeleniumOSSCube
 
Using existing language skillsets to create large-scale, cloud-based analytics
Using existing language skillsets to create large-scale, cloud-based analyticsUsing existing language skillsets to create large-scale, cloud-based analytics
Using existing language skillsets to create large-scale, cloud-based analyticsMicrosoft Tech Community
 
Advancing JavaScript with Libraries (Yahoo Tech Talk)
Advancing JavaScript with Libraries (Yahoo Tech Talk)Advancing JavaScript with Libraries (Yahoo Tech Talk)
Advancing JavaScript with Libraries (Yahoo Tech Talk)jeresig
 
Input output files in java
Input output files in javaInput output files in java
Input output files in javaKavitha713564
 
Utilizing the open ntf domino api
Utilizing the open ntf domino apiUtilizing the open ntf domino api
Utilizing the open ntf domino apiOliver Busse
 
20120601_Excel 元件 ep plus joncash
20120601_Excel 元件 ep plus joncash20120601_Excel 元件 ep plus joncash
20120601_Excel 元件 ep plus joncashLearningTech
 
Java Input Output and File Handling
Java Input Output and File HandlingJava Input Output and File Handling
Java Input Output and File HandlingSunil OS
 
CSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdfCSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdfVithalReddy3
 
Typical Architecture Of Automation Frameworks
Typical Architecture Of Automation FrameworksTypical Architecture Of Automation Frameworks
Typical Architecture Of Automation FrameworksYogindernath Gupta
 
Tanel Poder - Scripts and Tools short
Tanel Poder - Scripts and Tools shortTanel Poder - Scripts and Tools short
Tanel Poder - Scripts and Tools shortTanel Poder
 
Scripting as a Second Language
Scripting as a Second LanguageScripting as a Second Language
Scripting as a Second LanguageRob Dunn
 
Java IO Streams V4
Java IO Streams V4Java IO Streams V4
Java IO Streams V4Sunil OS
 
[DanNotes] XPages - Beyound the Basics
[DanNotes] XPages - Beyound the Basics[DanNotes] XPages - Beyound the Basics
[DanNotes] XPages - Beyound the BasicsUlrich Krause
 

Semelhante a Apache poi tutorial (20)

How to Read Excel Files in Java (1).pdf
How to Read Excel Files in Java (1).pdfHow to Read Excel Files in Java (1).pdf
How to Read Excel Files in Java (1).pdf
 
Exploiting JXL using Selenium
Exploiting JXL using SeleniumExploiting JXL using Selenium
Exploiting JXL using Selenium
 
Using existing language skillsets to create large-scale, cloud-based analytics
Using existing language skillsets to create large-scale, cloud-based analyticsUsing existing language skillsets to create large-scale, cloud-based analytics
Using existing language skillsets to create large-scale, cloud-based analytics
 
Advancing JavaScript with Libraries (Yahoo Tech Talk)
Advancing JavaScript with Libraries (Yahoo Tech Talk)Advancing JavaScript with Libraries (Yahoo Tech Talk)
Advancing JavaScript with Libraries (Yahoo Tech Talk)
 
Input output files in java
Input output files in javaInput output files in java
Input output files in java
 
Utilizing the open ntf domino api
Utilizing the open ntf domino apiUtilizing the open ntf domino api
Utilizing the open ntf domino api
 
20120601_Excel 元件 ep plus joncash
20120601_Excel 元件 ep plus joncash20120601_Excel 元件 ep plus joncash
20120601_Excel 元件 ep plus joncash
 
Data file handling
Data file handlingData file handling
Data file handling
 
Java Input Output and File Handling
Java Input Output and File HandlingJava Input Output and File Handling
Java Input Output and File Handling
 
Java I/O
Java I/OJava I/O
Java I/O
 
CSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdfCSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdf
 
Java I/O
Java I/OJava I/O
Java I/O
 
IOStream.pptx
IOStream.pptxIOStream.pptx
IOStream.pptx
 
Systemcall1
Systemcall1Systemcall1
Systemcall1
 
Typical Architecture Of Automation Frameworks
Typical Architecture Of Automation FrameworksTypical Architecture Of Automation Frameworks
Typical Architecture Of Automation Frameworks
 
5java Io
5java Io5java Io
5java Io
 
Tanel Poder - Scripts and Tools short
Tanel Poder - Scripts and Tools shortTanel Poder - Scripts and Tools short
Tanel Poder - Scripts and Tools short
 
Scripting as a Second Language
Scripting as a Second LanguageScripting as a Second Language
Scripting as a Second Language
 
Java IO Streams V4
Java IO Streams V4Java IO Streams V4
Java IO Streams V4
 
[DanNotes] XPages - Beyound the Basics
[DanNotes] XPages - Beyound the Basics[DanNotes] XPages - Beyound the Basics
[DanNotes] XPages - Beyound the Basics
 

Mais de Ramakrishna kapa

Mais de Ramakrishna kapa (20)

Load balancer in mule
Load balancer in muleLoad balancer in mule
Load balancer in mule
 
Anypoint connectors
Anypoint connectorsAnypoint connectors
Anypoint connectors
 
Batch processing
Batch processingBatch processing
Batch processing
 
Msmq connectivity
Msmq connectivityMsmq connectivity
Msmq connectivity
 
Scopes in mule
Scopes in muleScopes in mule
Scopes in mule
 
Data weave more operations
Data weave more operationsData weave more operations
Data weave more operations
 
Basic math operations using dataweave
Basic math operations using dataweaveBasic math operations using dataweave
Basic math operations using dataweave
 
Dataweave types operators
Dataweave types operatorsDataweave types operators
Dataweave types operators
 
Operators in mule dataweave
Operators in mule dataweaveOperators in mule dataweave
Operators in mule dataweave
 
Data weave in mule
Data weave in muleData weave in mule
Data weave in mule
 
Servicenow connector
Servicenow connectorServicenow connector
Servicenow connector
 
Introduction to testing mule
Introduction to testing muleIntroduction to testing mule
Introduction to testing mule
 
Choice flow control
Choice flow controlChoice flow control
Choice flow control
 
Message enricher example
Message enricher exampleMessage enricher example
Message enricher example
 
Mule exception strategies
Mule exception strategiesMule exception strategies
Mule exception strategies
 
Anypoint connector basics
Anypoint connector basicsAnypoint connector basics
Anypoint connector basics
 
Mule global elements
Mule global elementsMule global elements
Mule global elements
 
Mule message structure and varibles scopes
Mule message structure and varibles scopesMule message structure and varibles scopes
Mule message structure and varibles scopes
 
How to create an api in mule
How to create an api in muleHow to create an api in mule
How to create an api in mule
 
Log4j is a reliable, fast and flexible
Log4j is a reliable, fast and flexibleLog4j is a reliable, fast and flexible
Log4j is a reliable, fast and flexible
 

Último

W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfVishalKumarJha10
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfproinshot.com
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplatePresentation.STUDIO
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...kalichargn70th171
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...software pro Development
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 

Último (20)

W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 

Apache poi tutorial

  • 1. Apache POI Tutorial Apache POI is a popular API that allows programmers to create, modify, and display MS Office files using Java programs. It is an open source library developed and distributed by Apache Software Foundation to design or modify Microsoft Office files using Java program. The name POI was originally an acronym for Poor Obfuscation Implementation, referring humorously to the fact that the file formats seemed to be deliberately obfuscated, but poorly, since they were successfully reverse-engineered.
  • 2. • HSSF (Horrible SpreadSheet Format) – reads and writes Microsoft Excel (XLS) format files. • XSSF (XML SpreadSheet Format) – reads and writes Office Open XML (XLSX) format files. • HPSF (Horrible Property Set Format) – reads “Document Summary” information from Microsoft Office files. • HWPF (Horrible Word Processor Format) – aims to read and write Microsoft Word 97 (DOC) format files. • HSLF (Horrible Slide Layout Format) – a pure Java implementation for Microsoft PowerPoint files. • HDGF (Horrible DiaGram Format) – an initial pure Java implementation for Microsoft Visio binary files. • HPBF (Horrible PuBlisher Format) – a pure Java implementation for Microsoft Publisher files. • HSMF (Horrible Stupid Mail Format) – a pure Java implementation for Microsoft Outlook MSG files • DDF (Dreadful Drawing Format) – a package for decoding the Microsoft Office Drawing format.
  • 3. • Working with .xlsx files • The classes we used in above code snippet, HSSFWorkbook and HSSFSheet works for .xls format. In order to work with newer xls format viz .xlsx, you need to see newer POI classes like: • import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.xssf.usermodel.XSSFSheet; //.. FileInputStream file = new FileInputStream(new File("C:test.xlsx")); //Get the workbook instance for XLS file XSSFWorkbook workbook = new XSSFWorkbook (file); //Get first sheet from the workbook XSSFSheet sheet = workbook.getSheetAt(0); //Get iterator to all the rows in current sheet Iterator<Row> rowIterator = sheet.iterator(); //Get iterator to all cells of current row Iterator<Cell> cellIterator = row.cellIterator();
  • 4. Create Blank Workbook • The following simple program is used to create a blank Microsoft Excel Workbook. • import java.io.*; import org.apache.poi.xssf.usermodel.*; • public class CreateWorkBook { • public static void main(String[] args)throws Exception { • //Create Blank workbook • XSSFWorkbook workbook = new XSSFWorkbook(); //Create file system using specific name • FileOutputStream out = new FileOutputStream( new File("createworkbook.xlsx")); • //write operation workbook using file out object workbook.write(out); out.close(); System.out.println(" createworkbook.xlsx written successfully"); • } }
  • 5. Open Existing Workbook • Use the following code to open an existing workbook. • import java.io.*; import org.apache.poi.xssf.usermodel.*; • public class OpenWorkBook { • public static void main(String args[])throws Exception { File file = new File("openworkbook.xlsx"); FileInputStream fIP = new FileInputStream(file); • //Get the workbook instance for XLSX file • XSSFWorkbook workbook = new XSSFWorkbook(fIP); if(file.isFile() && file.exists()) • { System.out.println( "openworkbook.xlsx file open successfully."); • } else { System.out.println( "Error to open openworkbook.xlsx file."); } } }
  • 6. We will read above xls file using Apache POI and prints the data. • Consider a sample excel file: • test.xls
  • 7. • try { • • FileInputStream file = new FileInputStream(new File("C:test.xls")); • • //Get the workbook instance for XLS file • HSSFWorkbook workbook = new HSSFWorkbook(file); • //Get first sheet from the workbook • HSSFSheet sheet = workbook.getSheetAt(0); • • //Iterate through each rows from first sheet • Iterator<Row> rowIterator = sheet.iterator(); • while(rowIterator.hasNext()) { • Row row = rowIterator.next(); • • //For each row, iterate through each columns • Iterator<Cell> cellIterator = row.cellIterator(); • while(cellIterator.hasNext()) { • • Cell cell = cellIterator.next();
  • 8. • switch(cell.getCellType()) { • case Cell.CELL_TYPE_BOOLEAN: • System.out.print(cell.getBooleanCellValue() + "tt"); • break; • case Cell.CELL_TYPE_NUMERIC: • System.out.print(cell.getNumericCellValue() + "tt"); • break; • case Cell.CELL_TYPE_STRING: • System.out.print(cell.getStringCellValue() + "tt"); • break; • } • } • System.out.println(""); • }
  • 9. • file.close(); • FileOutputStream out = • new FileOutputStream(new File("C:test.xls")); • workbook.write(out); • out.close(); • • } catch (FileNotFoundException e) { • e.printStackTrace(); • } catch (IOException e) { • e.printStackTrace(); • }
  • 10. • 3. Create New Excel File • Let us create a new excel file and write data in it. Following is the API which we will use for this purpose. • import org.apache.poi.hssf.usermodel.HSSFSheet; • import org.apache.poi.hssf.usermodel.HSSFWorkbook; • //.. • HSSFWorkbook workbook = new HSSFWorkbook(); • HSSFSheet sheet = workbook.createSheet("Sample sheet"); • //Create a new row in current sheet • Row row = sheet.createRow(0); • //Create a new cell in current row • Cell cell = row.createCell(0); • //Set value to new value • cell.setCellValue("Blahblah");
  • 11. • Below is the complete code that writes a new excel with dummy data: • HSSFWorkbook workbook = new HSSFWorkbook(); • HSSFSheet sheet = workbook.createSheet("Sample sheet"); • • Map<String, Object[]> data = new HashMap<String, Object[]>(); • data.put("1", new Object[] {"Emp No.", "Name", "Salary"}); • data.put("2", new Object[] {1d, "John", 1500000d}); • data.put("3", new Object[] {2d, "Sam", 800000d}); • data.put("4", new Object[] {3d, "Dean", 700000d}); • • Set<String> keyset = data.keySet(); • int rownum = 0; • for (String key : keyset) { • Row row = sheet.createRow(rownum++); • Object [] objArr = data.get(key); • int cellnum = 0; • for (Object obj : objArr) { • Cell cell = row.createCell(cellnum++); • if(obj instanceof Date) • cell.setCellValue((Date)obj); • else if(obj instanceof Boolean) • cell.setCellValue((Boolean)obj); • else if(obj instanceof String) • cell.setCellValue((String)obj); • else if(obj instanceof Double) • cell.setCellValue((Double)obj); • } • } •
  • 12. • try { • FileOutputStream out = • new FileOutputStream(new File("C:new.xls")); • workbook.write(out); • out.close(); • System.out.println("Excel written successfully.."); • • } catch (FileNotFoundException e) { • e.printStackTrace(); • } catch (IOException e) { • e.printStackTrace(); • }