Read/write Excel file in Java using Apache POI

Source: Internet
Author: User

Read/write Excel file in Java using Apache POI

2014-04-18 by Dinesh LEAVE A COMMENT

About a year or both ago I was working with finance team where they wanted to pull the credit card transactions for all the The customer using various combinations. ex–

–get the credit card txns for today or certain date.

–get the Txns for customer, who used Mastercard or Visa.

However they wanted this application to generate a Excel file and save it in their local machine so that they could prepar E reports for our CEO. I used a Apache POI project to create jar files. This tutorial would walk you through the process of reading and writing Excel sheet. So let's see–how to read and write Excel files in Java?

Brief history on Apache POI

Apache POI is a powerful Java library to work with different Microsoft Office file formats such as Excel, Power Point, Vis Io, MS Word etc. The name POI was originally a acronym for Poor obfuscation implementation, referring humorously to the file formats that  Seemed deliberately obfuscated, but poorly, since they were successfully reverse-engineered. In short, you can read/write MS Excel files using Java. In addition, you can read/write Ms Word and Ms PowerPoint files using Java. Apache POI is your Java Excel solution.

Apache POI can be used to create both old (2003-2008) and new (2010–newer) format. I think the newer jar file to create XLSX document was out of BETA phase now. Back when I used the this POI it is still in Beta format.

So let's see how does it entails to read/write Excel files in Java.

I am Be is using Maven and IntelliJ to create my project, however is welcome to Useeclipse or Netbeans.

Apache POI Dependencies

There is different maven dependencies one for creating a older version of Excel–xls format and other for creating New version of EXCEL–XLSX format. I am listing both the dependencies here.

<dependencies>
<!–for Excel 2007–>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
</dependency>
</dependencies>

Create a new module in IntelliJ.

Add the dependency in your Pom.xml

PAUSE & Think:key POI CLASSES

Before we go ahead here's quick primer on 3 key classes in POI.

    1. Hssf–java implementation of the Excel ' ( -2007) file format. e.g. Hssfworkbook, Hssfsheet.
    2. Xssf–java implementation of the Excel OOXML (. xlsx) file format. e.g. Xssfworkbook, Xssfsheet.
    3. sxssf–used when very large spreadsheets has to be produced, and the heap space is limited. e.g. Sxssfworkbook, Sxssfsheet.

There is other wide range of classes as well which can is used to manipulate the Excel sheet. Ex–builtinformats, Conditionalformattingrule,comparisonoperator,cellstyle, fontformatting, IndexedColors, Patternformatting, sheetconditionalformatting. These used for formatting the sheet and formula evaluation.

How to CREATE A NEW EXCEL SHEET

This involves the following steps.

So go ahead and create a new file called Newexcel.java

Package Com.dinesh;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;import Java.io.File; Import Java.io.filenotfoundexception;import Java.io.fileoutputstream;import Java.io.ioexception;import Java.util.hashmap;import java.util.map;import java.util.set;import java.util.treemap;/** * Created by Darora on 4/18/ */public class Newexcel {public static void main (string[] args) {//create a new Workbook XSSFWORKBO        Ok workbook = new Xssfworkbook ();        Create a blank sheet xssfsheet sheet = workbook.createsheet ("Student data"); Create the data for the Excel sheet map<string, object[]= "" > data = new treemap<string, object[]= "" > (        );        Data.put ("1", new object[] {"ID", "FIRSTNAME", "LASTNAME"});        Data.put ("2", new object[] {1, "Randy", "Maven"}); Data.put ("3", new object[] {2, "Raymond", "Smith"});        Data.put ("4", new object[] {3, "Dinesh", "Arora"});        Data.put ("5", new object[] {4, "Barbra", "Klien"});        Iterate over data and write it to the sheet Set 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 String) cell.setcellvalue ((String) obj);            else if (obj instanceof Integer) cell.setcellvalue ((Integer) obj); }}//save the Excel sheet try{fileoutputstream out = new FileOutputStream ("c:\d            Inesh\javahabitexceldemo.xlsx "));            Workbook.write (out);            Out.close ();        System.out.println ("javahabitexceldemo.xlsx successfully created"); }catch (FileNotFoundException e) {e.printstacktrace ();        } catch (IOException e) {e.printstacktrace (); }    }}

OUTPUT

How to READ A NEW EXCEL SHEET

So now, we have the written an Excel sheet. Let's try to read it back.

The steps involved is

Package Com.dinesh;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;import Java.io.File; Import Java.io.fileinputstream;import Java.io.filenotfoundexception;import Java.io.ioexception;import java.util.iterator;/** * Created by Darora on 4/18/14.        */public class Readexcel {//create Workbook instance from Excel sheet public static void main (string[] args) { try {//get the Excel file FileInputStream file = new FileInputStream (The new file ("C:\Dinesh\javahab            Itexceldemo.xlsx "));            Xssfworkbook workbook = new Xssfworkbook (file);            Get the desired sheet xssfsheet sheet = workbook.getsheetat (0);                Increment over rows for (Row row:sheet) {//iterate and get the cells from the Row                Iterator celliterator = Row.celliterator (); Loop till you rEAD all the data while (Celliterator.hasnext ()) {Cell cell = Celliterator.next ();                            Switch (Cell.getcelltype ()) {case Cell.cell_type_numeric:                            System.out.print (Cell.getnumericcellvalue () + "T");                        Break                            Case Cell.CELL_TYPE_STRING:System.out.print (Cell.getstringcellvalue () + "T");                    Break            }} System.out.println ("");        } file.close ();        } catch (FileNotFoundException e) {e.printstacktrace ();        } catch (IOException e) {e.printstacktrace (); }    }}

OUTPUT

Using formulas in Excel sheet

When working on Excel sheets, we sometimes has to create cells which use formulas to calculate their values. Apache POI has supports methods for adding formula to cells and evaluating the already present formula in the cells. neat!!

So let's see an example on setting a formula cells in the Excel sheet.

In this code we'll try to calculate the simple interest. Formula–principal * Interest * time.

Package Com.dinesh;import Org.apache.poi.ss.usermodel.row;import Org.apache.poi.xssf.usermodel.xssfsheet;import Org.apache.poi.xssf.usermodel.xssfworkbook;import Java.io.file;import Java.io.filenotfoundexception;import Java.io.fileoutputstream;import java.io.ioexception;/** * Created by Darora on 4/18/14. */public class Calculateformula {public static void main (string[] args) {//create the workbook XSSFW        Orkbook workbook = new Xssfworkbook ();        Create the sheet xssfsheet sheet = workbook.createsheet ("Calculate simple Interest");        Create Wor Headers Row Header = sheet.createrow (0);        Header.createcell (0). Setcellvalue ("Principal");        Header.createcell (1). Setcellvalue ("Interest");        Header.createcell (2). Setcellvalue ("Time");        Header.createcell (3). Setcellvalue ("OUTPUT (P * R * t)");        Create the Rows Row dataRow = Sheet.createrow (1);        Datarow.createcell (0). Setcellvalue (1000d); Datarow.createceLL (1). Setcellvalue (12.00);        Datarow.createcell (2). Setcellvalue (6d);        Datarow.createcell (3). Setcellformula ("A2*b2*c2"); Save the file try {fileoutputstream out = new FileOutputStream ("C:\Dinesh\javahabitformulaD            Emo.xlsx "));            Workbook.write (out);            Out.close ();        System.out.println ("Excel File with FormLA is created!");        } catch (FileNotFoundException e) {e.printstacktrace ();        } catch (IOException e) {e.printstacktrace (); }    }}

OUTPUT

So experiment your IT with the This jar file and does post your comments and suggestions on topics you had like to see in my Fu Ture posts.

Recent POSTS
    • Powermock:how to test a private method
    • Install Or Manage Multiple versions of Java on OS X
    • Restful Webservice in 7 Steps using Spring boot
    • A Quick tutorial on SAAJ API
    • Read/write Excel file in Java using Apache POI
AUTHOR

I am Dinesh Arora, Java Developer, Go getter, Father and passionate about DIY and Blogging. Connect with me through Twitter

Recent POSTS
    • Powermock:how to test a private method
    • Install Or Manage Multiple versions of Java on OS X
    • Restful Webservice in 7 Steps using Spring boot
    • A Quick tutorial on SAAJ API
    • Read/write Excel file in Java using Apache POI

Read/write Excel file in Java using Apache POI

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.