SlideShare ist ein Scribd-Unternehmen logo
1 von 13
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Was ist angesagt?

Apache Solr + ajax solr
Apache Solr + ajax solrApache Solr + ajax solr
Apache Solr + ajax solrNet7
 
Introduction to Solr
Introduction to SolrIntroduction to Solr
Introduction to SolrErik Hatcher
 
Solr introduction
Solr introductionSolr introduction
Solr introductionLap Tran
 
Building your own search engine with Apache Solr
Building your own search engine with Apache SolrBuilding your own search engine with Apache Solr
Building your own search engine with Apache SolrBiogeeks
 
Introduction to Lucene and Solr - 1
Introduction to Lucene and Solr - 1Introduction to Lucene and Solr - 1
Introduction to Lucene and Solr - 1YI-CHING WU
 
code4lib 2011 preconference: What's New in Solr (since 1.4.1)
code4lib 2011 preconference: What's New in Solr (since 1.4.1)code4lib 2011 preconference: What's New in Solr (since 1.4.1)
code4lib 2011 preconference: What's New in Solr (since 1.4.1)Erik Hatcher
 
Beyond full-text searches with Lucene and Solr
Beyond full-text searches with Lucene and SolrBeyond full-text searches with Lucene and Solr
Beyond full-text searches with Lucene and SolrBertrand Delacretaz
 
Enterprise Search Solution: Apache SOLR. What's available and why it's so cool
Enterprise Search Solution: Apache SOLR. What's available and why it's so coolEnterprise Search Solution: Apache SOLR. What's available and why it's so cool
Enterprise Search Solution: Apache SOLR. What's available and why it's so coolEcommerce Solution Provider SysIQ
 
Lucene's Latest (for Libraries)
Lucene's Latest (for Libraries)Lucene's Latest (for Libraries)
Lucene's Latest (for Libraries)Erik Hatcher
 
Lifecycle of a Solr Search Request - Chris "Hoss" Hostetter, Lucidworks
Lifecycle of a Solr Search Request - Chris "Hoss" Hostetter, LucidworksLifecycle of a Solr Search Request - Chris "Hoss" Hostetter, Lucidworks
Lifecycle of a Solr Search Request - Chris "Hoss" Hostetter, LucidworksLucidworks
 
Rapid Prototyping with Solr
Rapid Prototyping with SolrRapid Prototyping with Solr
Rapid Prototyping with SolrErik Hatcher
 
Solr Black Belt Pre-conference
Solr Black Belt Pre-conferenceSolr Black Belt Pre-conference
Solr Black Belt Pre-conferenceErik Hatcher
 
Solr Recipes Workshop
Solr Recipes WorkshopSolr Recipes Workshop
Solr Recipes WorkshopErik Hatcher
 
Integrating the Solr search engine
Integrating the Solr search engineIntegrating the Solr search engine
Integrating the Solr search engineth0masr
 
Rapid Prototyping with Solr
Rapid Prototyping with SolrRapid Prototyping with Solr
Rapid Prototyping with SolrErik Hatcher
 
Solr Indexing and Analysis Tricks
Solr Indexing and Analysis TricksSolr Indexing and Analysis Tricks
Solr Indexing and Analysis TricksErik Hatcher
 

Was ist angesagt? (20)

Apache Solr + ajax solr
Apache Solr + ajax solrApache Solr + ajax solr
Apache Solr + ajax solr
 
Introduction to Solr
Introduction to SolrIntroduction to Solr
Introduction to Solr
 
Solr introduction
Solr introductionSolr introduction
Solr introduction
 
Solr Masterclass Bangkok, June 2014
Solr Masterclass Bangkok, June 2014Solr Masterclass Bangkok, June 2014
Solr Masterclass Bangkok, June 2014
 
Building your own search engine with Apache Solr
Building your own search engine with Apache SolrBuilding your own search engine with Apache Solr
Building your own search engine with Apache Solr
 
Introduction to Lucene and Solr - 1
Introduction to Lucene and Solr - 1Introduction to Lucene and Solr - 1
Introduction to Lucene and Solr - 1
 
Building a Search Engine Using Lucene
Building a Search Engine Using LuceneBuilding a Search Engine Using Lucene
Building a Search Engine Using Lucene
 
code4lib 2011 preconference: What's New in Solr (since 1.4.1)
code4lib 2011 preconference: What's New in Solr (since 1.4.1)code4lib 2011 preconference: What's New in Solr (since 1.4.1)
code4lib 2011 preconference: What's New in Solr (since 1.4.1)
 
Beyond full-text searches with Lucene and Solr
Beyond full-text searches with Lucene and SolrBeyond full-text searches with Lucene and Solr
Beyond full-text searches with Lucene and Solr
 
Enterprise Search Solution: Apache SOLR. What's available and why it's so cool
Enterprise Search Solution: Apache SOLR. What's available and why it's so coolEnterprise Search Solution: Apache SOLR. What's available and why it's so cool
Enterprise Search Solution: Apache SOLR. What's available and why it's so cool
 
Lucene's Latest (for Libraries)
Lucene's Latest (for Libraries)Lucene's Latest (for Libraries)
Lucene's Latest (for Libraries)
 
Lifecycle of a Solr Search Request - Chris "Hoss" Hostetter, Lucidworks
Lifecycle of a Solr Search Request - Chris "Hoss" Hostetter, LucidworksLifecycle of a Solr Search Request - Chris "Hoss" Hostetter, Lucidworks
Lifecycle of a Solr Search Request - Chris "Hoss" Hostetter, Lucidworks
 
Rapid Prototyping with Solr
Rapid Prototyping with SolrRapid Prototyping with Solr
Rapid Prototyping with Solr
 
Solr Black Belt Pre-conference
Solr Black Belt Pre-conferenceSolr Black Belt Pre-conference
Solr Black Belt Pre-conference
 
Solr Recipes Workshop
Solr Recipes WorkshopSolr Recipes Workshop
Solr Recipes Workshop
 
Integrating the Solr search engine
Integrating the Solr search engineIntegrating the Solr search engine
Integrating the Solr search engine
 
Rapid Prototyping with Solr
Rapid Prototyping with SolrRapid Prototyping with Solr
Rapid Prototyping with Solr
 
Apache Solr
Apache SolrApache Solr
Apache Solr
 
Annotations
AnnotationsAnnotations
Annotations
 
Solr Indexing and Analysis Tricks
Solr Indexing and Analysis TricksSolr Indexing and Analysis Tricks
Solr Indexing and Analysis Tricks
 

Ähnlich wie Apachepoitutorial

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
 
Utilizing the open ntf domino api
Utilizing the open ntf domino apiUtilizing the open ntf domino api
Utilizing the open ntf domino apiOliver Busse
 
CSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdfCSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdfVithalReddy3
 
Java Input Output and File Handling
Java Input Output and File HandlingJava Input Output and File Handling
Java Input Output and File HandlingSunil OS
 
Input output files in java
Input output files in javaInput output files in java
Input output files in javaKavitha713564
 
20120601_Excel 元件 ep plus joncash
20120601_Excel 元件 ep plus joncash20120601_Excel 元件 ep plus joncash
20120601_Excel 元件 ep plus joncashLearningTech
 
Tanel Poder - Scripts and Tools short
Tanel Poder - Scripts and Tools shortTanel Poder - Scripts and Tools short
Tanel Poder - Scripts and Tools shortTanel Poder
 
Utilizing the OpenNTF Domino API
Utilizing the OpenNTF Domino APIUtilizing the OpenNTF Domino API
Utilizing the OpenNTF Domino APIOliver Busse
 
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
 

Ähnlich wie Apachepoitutorial (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)
 
Utilizing the open ntf domino api
Utilizing the open ntf domino apiUtilizing the open ntf domino api
Utilizing the open ntf domino api
 
CSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdfCSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdf
 
Java Input Output and File Handling
Java Input Output and File HandlingJava Input Output and File Handling
Java Input Output and File Handling
 
Data file handling
Data file handlingData file handling
Data file handling
 
Input output files in java
Input output files in javaInput output files in java
Input output files in java
 
Java I/O
Java I/OJava I/O
Java I/O
 
20120601_Excel 元件 ep plus joncash
20120601_Excel 元件 ep plus joncash20120601_Excel 元件 ep plus joncash
20120601_Excel 元件 ep plus joncash
 
IOStream.pptx
IOStream.pptxIOStream.pptx
IOStream.pptx
 
Tanel Poder - Scripts and Tools short
Tanel Poder - Scripts and Tools shortTanel Poder - Scripts and Tools short
Tanel Poder - Scripts and Tools short
 
Java I/O
Java I/OJava I/O
Java I/O
 
Utilizing the OpenNTF Domino API
Utilizing the OpenNTF Domino APIUtilizing the OpenNTF Domino API
Utilizing the OpenNTF Domino API
 
5java Io
5java Io5java Io
5java Io
 
Systemcall1
Systemcall1Systemcall1
Systemcall1
 
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
 

Mehr von Srikrishna k

Mehr von Srikrishna k (16)

Android
AndroidAndroid
Android
 
Hsqldb tutorial
Hsqldb tutorialHsqldb tutorial
Hsqldb tutorial
 
S3inmule
S3inmuleS3inmule
S3inmule
 
Mule sqs
Mule sqsMule sqs
Mule sqs
 
Introduction testingmule
Introduction testingmuleIntroduction testingmule
Introduction testingmule
 
Designpattern
DesignpatternDesignpattern
Designpattern
 
Java util
Java utilJava util
Java util
 
Kafka tutorial
Kafka tutorialKafka tutorial
Kafka tutorial
 
Test ng tutorial
Test ng tutorialTest ng tutorial
Test ng tutorial
 
Webservices intro
Webservices introWebservices intro
Webservices intro
 
Easy mock
Easy mockEasy mock
Easy mock
 
Apache kafka
Apache kafkaApache kafka
Apache kafka
 
Apachespark 160612140708
Apachespark 160612140708Apachespark 160612140708
Apachespark 160612140708
 
Vmtransport 160723040146
Vmtransport 160723040146Vmtransport 160723040146
Vmtransport 160723040146
 
Groovydemo 160721051742
Groovydemo 160721051742Groovydemo 160721051742
Groovydemo 160721051742
 
Apache kafka
Apache kafkaApache kafka
Apache kafka
 

Kürzlich hochgeladen

Large Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLarge Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLionel Briand
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsSafe Software
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfDrew Moseley
 
Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecturerahul_net
 
Leveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + KobitonLeveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + KobitonApplitools
 
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full RecordingOpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full RecordingShane Coughlan
 
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...Bert Jan Schrijver
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZABSYZ Inc
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Rob Geurden
 
eSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolseSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolsosttopstonverter
 
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...OnePlan Solutions
 
Introduction to Firebase Workshop Slides
Introduction to Firebase Workshop SlidesIntroduction to Firebase Workshop Slides
Introduction to Firebase Workshop Slidesvaideheekore1
 
Keeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldKeeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldRoberto Pérez Alcolea
 
SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?Alexandre Beguel
 
Best Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh ITBest Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh ITmanoharjgpsolutions
 
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfEnhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfRTS corp
 
2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shardsChristopher Curtin
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalLionel Briand
 
Patterns for automating API delivery. API conference
Patterns for automating API delivery. API conferencePatterns for automating API delivery. API conference
Patterns for automating API delivery. API conferencessuser9e7c64
 
Strategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsStrategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsJean Silva
 

Kürzlich hochgeladen (20)

Large Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLarge Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and Repair
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data Streams
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdf
 
Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecture
 
Leveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + KobitonLeveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
 
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full RecordingOpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
 
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZ
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...
 
eSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolseSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration tools
 
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
 
Introduction to Firebase Workshop Slides
Introduction to Firebase Workshop SlidesIntroduction to Firebase Workshop Slides
Introduction to Firebase Workshop Slides
 
Keeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldKeeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository world
 
SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?
 
Best Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh ITBest Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh IT
 
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfEnhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
 
2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive Goal
 
Patterns for automating API delivery. API conference
Patterns for automating API delivery. API conferencePatterns for automating API delivery. API conference
Patterns for automating API delivery. API conference
 
Strategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsStrategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero results
 

Apachepoitutorial

  • 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(); • }