Apache POI – Read and Write Excel File in Java

Learn to read excel, write excel, evaluate formula cells and apply custom formatting to the generated excel files using Apache POI library with examples.

If we are building a software for the HR or the Finance domain, there is usually a requirement for generating the excel reports, usually across management levels. Apart from reports, we can also expect some input data for the applications coming in the form of excel sheets and the application is expected to support this requirement.

Apache POI is a well-trusted library among many other open-source libraries to handle such usecases involving excel files. Please note that, in addition, we can read and write MS Word and MS PowerPoint files also using the Apache POI library.

In this Apache POI tutorial, We will discuss some common excel operations in real-life applications.

1. Maven Dependency

If we are working on a maven project, we can include the POI dependency in pom.xml file using this:


If we are not using maven, then we can find the required jar files from the zip file available in this location. Include all the jar files into the application lib folder to run the sample code given in this tutorial.

2. Important Classes in POI Library

  1. HSSF, XSSF and XSSF classes

    Apache POI main classes usually start with either HSSF, XSSF or SXSSF.

    • HSSF – is the POI Project’s pure Java implementation of the Excel ’97(-2007) file format. e.g. HSSFWorkbook, HSSFSheet.
    • XSSF – is the POI Project’s pure Java implementation of the Excel 2007 OOXML (.xlsx) file format. e.g. XSSFWorkbook, XSSFSheet.
    • SXSSF (since 3.8-beta3) – is an API-compatible streaming extension of XSSF to be used when very large spreadsheets have to be produced, and heap space is limited. e.g. SXSSFWorkbook, SXSSFSheet. SXSSF achieves its low memory footprint by limiting access to the rows that are within a sliding window, while XSSF gives access to all rows in the document.
  2. Row and Cell

    Apart from above classes, Row and Cell are used to interact with a particular row and a particular cell in excel sheet.

  3. Styling Related Classes

    A wide range of classes like CellStyle, BuiltinFormats, ComparisonOperator, ConditionalFormattingRule, FontFormatting, IndexedColors, PatternFormatting, SheetConditionalFormatting etc. are used when you have to add formatting in a sheet, mostly based on some rules.

  4. FormulaEvaluator

    Another useful class FormulaEvaluator is used to evaluate the formula cells in excel sheet.

3. Writing an Excel File

I am taking this example first so that we can reuse the excel sheet created by this code in further examples.

Writing excel using POI is very simple and involve the following steps:

  1. Create a workbook
  2. Create a sheet in workbook
  3. Create a row in sheet
  4. Add cells in sheet
  5. Repeat step 3 and 4 to write more data

It seems very simple, right? Let’s have a look at the code doing these steps.

Java program to write an excel file using Apache POI library.

package com.howtodoinjava.demo.poi;
//import statements
public class WriteExcelDemo 
    public static void main(String[] args) 
        //Blank workbook
        XSSFWorkbook workbook = new XSSFWorkbook(); 
        //Create a blank sheet
        XSSFSheet sheet = workbook.createSheet("Employee Data");
        //This data needs to be written (Object[])
        Map<String, Object[]> data = new TreeMap<String, Object[]>();
        data.put("1", new Object[] {"ID", "NAME", "LASTNAME"});
        data.put("2", new Object[] {1, "Amit", "Shukla"});
        data.put("3", new Object[] {2, "Lokesh", "Gupta"});
        data.put("4", new Object[] {3, "John", "Adwards"});
        data.put("5", new Object[] {4, "Brian", "Schultz"});
        //Iterate over data and write to sheet
        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 String)
                else if(obj instanceof Integer)
            //Write the workbook in file system
            FileOutputStream out = new FileOutputStream(new File("howtodoinjava_demo.xlsx"));
            System.out.println("howtodoinjava_demo.xlsx written successfully on disk.");
        catch (Exception e) 

4. Reading an Excel File

Reading an excel file using POI is also very simple if we divide this into steps.

  1. Create workbook instance from excel sheet
  2. Get to the desired sheet
  3. Increment row number
  4. iterate over all cells in a row
  5. repeat step 3 and 4 until all data is read

Let’s see all the above steps in code. I am writing the code to read the excel file created in the above example. It will read all the column names and the values in it – cell by cell.

Java program to read an excel file using Apache POI library.

package com.howtodoinjava.demo.poi;
//import statements
public class ReadExcelDemo 
    public static void main(String[] args) 
            FileInputStream file = new FileInputStream(new File("howtodoinjava_demo.xlsx"));
            //Create Workbook instance holding reference to .xlsx file
            XSSFWorkbook workbook = new XSSFWorkbook(file);
            //Get first/desired sheet from the workbook
            XSSFSheet sheet = workbook.getSheetAt(0);
            //Iterate through each rows one by one
            Iterator<Row> rowIterator = sheet.iterator();
            while (rowIterator.hasNext()) 
                Row row = rowIterator.next();
                //For each row, iterate through all the columns
                Iterator<Cell> cellIterator = row.cellIterator();
                while (cellIterator.hasNext()) 
                    Cell cell = cellIterator.next();
                    //Check the cell type and format accordingly
                    switch (cell.getCellType()) 
                        case Cell.CELL_TYPE_NUMERIC:
                            System.out.print(cell.getNumericCellValue() + "t");
                        case Cell.CELL_TYPE_STRING:
                            System.out.print(cell.getStringCellValue() + "t");
        catch (Exception e) 

Program Output:

ID      NAME        LASTNAME
1.0     Amit        Shukla  
2.0     Lokesh      Gupta   
3.0     John        Adwards 
4.0     Brian       Schultz 

5. Add and Evaluate Formula Cells

When working on complex excel sheets, we encounter many cells which have formulas to calculate their values. These are formula cells. Apache POI has excellent support for adding formula cells and evaluating already present formula cells also.

Let’s see one example of how to add formula cells in excel?

In this code, there are four cells in a row and the fourth one in the multiplication of all previous 3 rows. So the formula will be: A2*B2*C2 (in the second row)

Java program to add formula in an excel file using Apache POI library.

public static void main(String[] args) 
    XSSFWorkbook workbook = new XSSFWorkbook();
    XSSFSheet sheet = workbook.createSheet("Calculate Simple Interest");
    Row header = sheet.createRow(0);
    header.createCell(3).setCellValue("Interest (P r t)");
    Row dataRow = sheet.createRow(1);
    try {
        FileOutputStream out =  new FileOutputStream(new File("formulaDemo.xlsx"));
        System.out.println("Excel with foumula cells written successfully");
    } catch (FileNotFoundException e) {
    } catch (IOException e) {

Similarly, we want to read a file with formula cells and use the following logic to evaluate formula cells.

Java program to evaluate formula in an excel file using Apache POI library.

public static void readSheetWithFormula()
        FileInputStream file = new FileInputStream(new File("formulaDemo.xlsx"));
        //Create Workbook instance holding reference to .xlsx file
        XSSFWorkbook workbook = new XSSFWorkbook(file);
        FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
        //Get first/desired sheet from the workbook
        XSSFSheet sheet = workbook.getSheetAt(0);
        //Iterate through each rows one by one
        Iterator<Row> rowIterator = sheet.iterator();
        while (rowIterator.hasNext()) 
            Row row = rowIterator.next();
            //For each row, iterate through all the columns
            Iterator<Cell> cellIterator = row.cellIterator();
            while (cellIterator.hasNext()) 
                Cell cell = cellIterator.next();
                //Check the cell type after eveluating formulae
                //If it is formula cell, it will be evaluated otherwise no change will happen
                switch (evaluator.evaluateInCell(cell).getCellType()) 
                    case Cell.CELL_TYPE_NUMERIC:
                        System.out.print(cell.getNumericCellValue() + "tt");
                    case Cell.CELL_TYPE_STRING:
                        System.out.print(cell.getStringCellValue() + "tt");
                    case Cell.CELL_TYPE_FORMULA:
                        //Not again
    catch (Exception e) 

Program Output:

Pricipal        RoI         T       Interest (P r t)        
14500.0         9.25        3.0     402375.0  

6. Formatting the Cells

So for we have seen the examples of reading/writing and excel files using Apache POI. But, when creating a report in an excel file, it becomes of utmost importance to add formatting on cells that fit into any pre-determined criteria.

This formatting can be a different coloring based on a specific value range, based on expiry date limit etc.

In the below examples, we are taking a couple of such cell formatting examples for various purposes.

6.1. Cell value in a certain range

This piece of code will color any cell in a range whose value is between a configured range. [e.g., between 50 and 70]

static void basedOnValue(Sheet sheet) 
    //Creating some random values
    SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting();
    //Condition 1: Cell Value Is   greater than  70   (Blue Fill)
    ConditionalFormattingRule rule1 = sheetCF.createConditionalFormattingRule(ComparisonOperator.GT, "70");
    PatternFormatting fill1 = rule1.createPatternFormatting();
    //Condition 2: Cell Value Is  less than      50   (Green Fill)
    ConditionalFormattingRule rule2 = sheetCF.createConditionalFormattingRule(ComparisonOperator.LT, "50");
    PatternFormatting fill2 = rule2.createPatternFormatting();
    CellRangeAddress[] regions = {
    sheetCF.addConditionalFormatting(regions, rule1, rule2);

6.2. Highlight Duplicate Values

Highlight all cells which have duplicate values in observed cells.

static void formatDuplicates(Sheet sheet) {
    SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting();
    // Condition 1: Formula Is   =A2=A1   (White Font)
    ConditionalFormattingRule rule1 = sheetCF.createConditionalFormattingRule("COUNTIF($A$2:$A$11,A2)>1");
    FontFormatting font = rule1.createFontFormatting();
    font.setFontStyle(false, true);
    CellRangeAddress[] regions = {
    sheetCF.addConditionalFormatting(regions, rule1);
    sheet.getRow(2).createCell(1).setCellValue("<== Duplicates numbers in the column are highlighted.  " +
            "Condition: Formula Is =COUNTIF($A$2:$A$11,A2)>1   (Blue Font)");

6.3. Color Alternate Rows in Different Colors

A simple code to color each alternate row in a different color.

static void shadeAlt(Sheet sheet) {
    SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting();
    // Condition 1: Formula Is   =A2=A1   (White Font)
    ConditionalFormattingRule rule1 = sheetCF.createConditionalFormattingRule("MOD(ROW(),2)");
    PatternFormatting fill1 = rule1.createPatternFormatting();
    CellRangeAddress[] regions = {
    sheetCF.addConditionalFormatting(regions, rule1);
    sheet.createRow(0).createCell(1).setCellValue("Shade Alternating Rows");
    sheet.createRow(1).createCell(1).setCellValue("Condition: Formula Is  =MOD(ROW(),2)   (Light Green Fill)");

6.4. Color amounts which are going to expire in next 30 days

A handy code for financial projects which keeps track of deadlines.

static void expiryInNext30Days(Sheet sheet) 
    CellStyle style = sheet.getWorkbook().createCellStyle();
    for(int rownum = 1; rownum <= 3; rownum++) sheet.getRow(rownum).getCell(0).setCellStyle(style);
    SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting();
    // Condition 1: Formula Is   =A2=A1   (White Font)
    ConditionalFormattingRule rule1 = sheetCF.createConditionalFormattingRule("AND(A2-TODAY()>=0,A2-TODAY()<=30)");
    FontFormatting font = rule1.createFontFormatting();
    font.setFontStyle(false, true);
    CellRangeAddress[] regions = {
    sheetCF.addConditionalFormatting(regions, rule1);
    sheet.getRow(0).createCell(1).setCellValue("Dates within the next 30 days are highlighted");

I am ending this apache poi tutorial here for keeping the post in limit.

7. Download Sourcecode

Click on the given link to download the source code of the above examples.

In this tutorial, we learned to read excel, write excel, set and evaluate formula cells, and format the cells with color codings using the Apache POI library.

Happy Learning !!


Apache POI How-to Guide
Apache POI API docs

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

181 thoughts on “Apache POI – Read and Write Excel File in Java”

  1. Hi,

    I have excel sheet with columns like this( Asset Name , Asset Type, Asset SubType , Asset Logo Path)… Here I want to read blob data based on Asset Logo Path column(/home/mbytes/yellaiah/asset imgs/pens.png) value to back-end(spring) from front-end extjs grid. I have tested reading file based on asset logo path column value, blob data is reading if client and server both are in same system, but i want to upload excel sheet from system2 by connecting to my server system and read files from local system(based on uploaded system) and insert into db. when i upload excel sheet i am display uploaded data to extjs grid. in grid i have button. when i click on button i need to pass data to back-end.how can i read blob from other system. pls give some suggestions.

  2. Some of the istorm reports are not working correctly in Excel 365.Which version of POI.jar supports excel 365?Kindly help me.

  3. Hi Lokesh, it was very helpful. Thanks for your help. I have a question on your second example;

    Reading an excel file:

    instead of getting all the cell values, what if want to get an input from an user (getText), lets say : ID – 1 and I need those cell values i.e. Amit and Shukla? Please throw some light on this.

  4. Hi Mr.Lokesh,
    Thanks for the helpful work uploaded.

    Also, can u plz let me know can i read & write simultaneously from an excel file using Java, keeping the file open ?

  5. Hi,

    I am abel to write data in excel using above code, but when I open the file I am getting Data like :

    3.0 John Adwards
    4.0 Brian Schultz
    1.0 Amit Shukla
    2.0 Lokesh Gupta

    any idea?

  6. Need the suggestion regarding the below..

    reading the above created file, howtodoinjava_demo.xlsx.

    while parsing by using SAX Parser, the output is differing the output as below.

    Employee Data [index=0]:

    Same file just edited in local system and doing the same gives the below output – looks fine.

    Employee Data [index=0]:

    Please advise what can we do to get same results with system generated file?

  7. Hi Lokesh,
    I am stuck in 1 requirement to upload an read excel and save it in db.

    Problem: i have n no. of excel sheets and all have different columns and all sheets would save in different table (having different table structure). And i want to create a common service , which read excel sheets and save accordingly.

    • In that case, you MUST put some restriction for users who are uploading those files. E.g. File names should include a particular word for each different format, OR column names should match exactly what is specified. There MUST be some rule which could be verified after file is received at server side.

      • Hi Lokesh, Thanks for the reply. I should elaborate more of my problem, to understand u in clear way:

        For Example I have 3 excel tabs A, B & C. A has 5 columns, B has 10 & C has 15 columns. As of now, i am creating 3 different beans with the same no. of attributes (Setter/Getter) , sets every column and finally save the object in db(using hibernate).

        But using this concept, i need to create 3 different service for 3 different tabs.

        SO, is there any optimize way of doing this.

        • I will suggest you to stick with 3 services. It is good for future use.
          See, it’s more of coding style question. I believe that code should be easy enough to read AND follow these SOLID principles. I will prefer easy maintainable code, rather than optimized code. Choice is yours.

  8. i want to read data from excel sheet using range. suppose we want to read cell range A1:C12. please suggest me how read using cell range.


  9. Hi Lokesh,

    The way evaluates return formulas is seriously baffling to me, and it’s disturbing me a little bit! When reading how this is done I didn’t quite believe it would work, here is the code where I’ve used the technique:

    private Object getCellValue(Cell cell) {

    int cellType = evaluator.evaluateInCell(cell).getCellType();

    if (cellType == Cell.CELL_TYPE_STRING ) return cell.getStringCellValue ();
    else if (cellType == Cell.CELL_TYPE_NUMERIC) return cell.getNumericCellValue();
    else if (cellType == Cell.CELL_TYPE_FORMULA) return null ;
    else if (cellType == Cell.CELL_TYPE_BOOLEAN) return cell.getBooleanCellValue();
    else if (cellType == Cell.CELL_TYPE_ERROR ) return cell.getErrorCellValue ();

    return "";

    So despite returning null when I have a formula, the evaluation of the formula is automatically returned? But it was also automatically written to the file in your example above… For example I am grabbing data into arrays to use in an application and the array is automatically populated from the use of this function…

    Spooky! Would be interested in knowing how this works :).

  10.  while reading xlsx file i have following exceptions 
    org.apache.poi.POIXMLException: java.lang.reflect.InvocationTargetException
    	at org.apache.poi.xssf.usermodel.XSSFFactory.createDocumentPart(XSSFFactory.java:62)
    	at org.apache.poi.POIXMLDocumentPart.read(POIXMLDocumentPart.java:403)
    	at org.apache.poi.POIXMLDocument.load(POIXMLDocument.java:155)
    	at org.apache.poi.xssf.usermodel.XSSFWorkbook.&lt;init&gt;(XSSFWorkbook.java:207)
    	at com.howtodoinjava.demo.poi.ReadExcelDemo.main(ReadExcelDemo.java:23)
    Caused by: java.lang.reflect.InvocationTargetException
    	at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    	at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    	at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    	at java.lang.reflect.Constructor.newInstance(Unknown Source)
    	at org.apache.poi.xssf.usermodel.XSSFFactory.createDocumentPart(XSSFFactory.java:60)
    	... 4 more
    Caused by: java.lang.IllegalStateException: Using in a JDK without an SHA implementation
    	at org.apache.xmlbeans.impl.common.QNameHelper.hexsafe(QNameHelper.java:170)
    	at org.apache.xmlbeans.impl.common.QNameHelper.hexsafedir(QNameHelper.java:178)
    	at org.apache.xmlbeans.impl.schema.SchemaTypeLoaderImpl.typeSystemForComponent(SchemaTypeLoaderImpl.java:249)
    	at org.apache.xmlbeans.impl.schema.SchemaTypeLoaderImpl.findDocumentTypeRef(SchemaTypeLoaderImpl.java:430)
    	at org.apache.xmlbeans.impl.schema.SchemaTypeLoaderBase.findDocumentType(SchemaTypeLoaderBase.java:129)
    	at org.apache.xmlbeans.impl.store.Locale.autoTypeDocument(Locale.java:312)
    	at org.apache.xmlbeans.impl.store.Locale.parseToXmlObject(Locale.java:1273)
    	at org.apache.xmlbeans.impl.store.Locale.parseToXmlObject(Locale.java:1257)
    	at org.apache.xmlbeans.impl.schema.SchemaTypeLoaderBase.parse(SchemaTypeLoaderBase.java:345)
    	at org.openxmlformats.schemas.spreadsheetml.x2006.main.SstDocument$Factory.parse(Unknown Source)
    	at org.apache.poi.xssf.model.SharedStringsTable.readFrom(SharedStringsTable.java:115)
    	at org.apache.poi.xssf.model.SharedStringsTable.&lt;init&gt;(SharedStringsTable.java:102)
    	... 9 more
    please help me to solve this problem as i m very new to java. thanks in advance 
  11. Hi Lokesh,

    I’m getting the column name and corresponding values dynamically. I don’t want to hard code both column name and values.
    Below method will get the list of users which will have column names and values.
    List mystring = getIndiviualRecordsList(getLdapDirContext());
    I’m wondering how to use it here. Please share your thoughts.
    //This data needs to be written (Object[])
    Map data = new TreeMap();
    data.put(“1”, new Object[] {“ID”, “NAME”, “LASTNAME”});
    data.put(“2”, new Object[] {1, “Amit”, “Shukla”});
    data.put(“3”, new Object[] {2, “Lokesh”, “Gupta”});
    data.put(“4”, new Object[] {3, “John”, “Adwards”});
    data.put(“5”, new Object[] {4, “Brian”, “Schultz”});

  12. Hi Guptha,

    Id FirstName LastName City
    10 Anjali K Pune
    20 Pavani D Delhi
    30 Anusha L Mumbai

    I have Sample .Excel sheet with the above columns and data.I want to display this data in Jtable.Right now am able to display hardcoded data in the Jtable through Controller.But am not able to display through excel sheet.Can you please tell me how to do that ?

    Thanks Advance

  13. Hi Lokesh,

    I have a sheet which have few columns , and I have to compare all the cells of the specific column by column’s heading name instead by its index value, can you guide me regarding this.


  14. solved the problem when i removed my imports and add the default
    there are :
    import org.apache.commons.io.FilenameUtils;
    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 org.primefaces.event.FileUploadEvent;
    import org.primefaces.model.UploadedFile;

  15. i have genetated a .xls file and i am abls to save it by “FileOutputStream out = new FileOutputStream(new File(“DirName:\FolderName\fileName.xls”)); ” but i want it through GUI..

  16. How to save generated xls file at specified location ..means the path should be given by user where he want to save it??????

  17. Thanx man…. Covered all topics and more importantly code……… good work……… keep it up

  18. I am using J2EE 5.0 and jboss 5.1.0 and EJB 2.0 I have added follwing jars in lib folder and to the classpath of the project:-


    When i try to deploy and run the application it is showing
    java.lang.ClassNotFoundException: org.apache.poi.xssf.usermodel.XSSFWorkbook from BaseClassLoader

  19. Hey buddy.. Finally found the solution by adding the Below dependencies in the pom.xml






  20. Hi Lokesh,
    Definately you have explained the things very well. But, I am completely struck at the step of handling xssf file. I am using maven and as suggested above, in my pom.xml file, I have added the below dependencies.



    But, when I try to run any of the simple tests after this, it gives me the error as :- java.lang.NoClassDefFoundError: org/w3c/dom/ElementTraversal

    However, on removing the second dependency i.e. poi-ooxml, the other test classes work fine, but the excel code file shows error for xssf.
    Please suggest some solution on it. I am completely struck on this issue.
    My requirement is basically to add data from the second row of a particular sheet of the downloaded .xlsx file and then upload this excel file again to the application. I am referring the above code for updating the downloaded excel file. Also, It would be great if you can provide some existing code for such scenario.

    Thanks & Regards,

  21. i want to retrieve data from database to excelsheet i am able to do that but if that detail in database is having more details then cell size is not getting increase so how to increase the cell size according to field value can you help me sir..?

  22. Hi Lokesh,

    I am trying to create an Excel file but when my java class do

    XSSFWorkbook workbook = new XSSFWorkbook();

    I get the error

    java.lang.ClassNotFoundException: Cannot find class ‘org.apache.xmlbeans.impl.regex.message’
    java.lang.ClassNotFoundException: Cannot find class ‘org.apache.xmlbeans.impl.regex.message_en’
    java.lang.ClassNotFoundException: Cannot find class ‘org.apache.xmlbeans.impl.regex.message_en_US’

    However I cant find any message.class in xmlbeans-2.3.0.jar.

    Do you have any idea why I get these errors.


      • My java class is in a jarfile together with the jarfiles containing the referenced classes. The manifest looks like:

        Manifest-Version: 1.0
        Ant-Version: Apache Ant 1.6.5
        Created-By: 1.4.2_15-b02 (Sun Microsystems Inc.)
        Transformer-class: CSendGlobalSuppliersToJcat
        Class-Path: dom4j-1.6.1.jar poi-3.7-20101029.jar
        poi-ooxml-3.7-20101029.jar poi-ooxml-schemas-3.7-20101029.jar
        xmlbeans-2.3.0.jar cjcatalogintegration.jar

        I have also tried with the latest versions of the poi files but with the same error.


          • Hi Lokesh,

            I have tried with both 2.4.0 and 2.6.0 with the same error.

            The error message is “ClassNotFoundException: cannot find class ‘org.apache.xmlbeans.impl.regex.message'” but I dont think this is the problem. The error message refere to ‘org.apache.xmlbeans.impl.regex.message’ which is not a class.

            Might be some problem in language or territory configuration. I dont know.

          • Yes, there are 4 files present:


            The error message refere to


            Same in all versions.

          • Problem is solved. The classloader failed to load resource files. The error message was confusing. Code works fine. Thanks.

  23. Lokesh:

    I want to have multiple XLS report files with charts be merged into one XLS file with multiple worksheets.

    For example I have file1.xlsx with 3 worksheets with charts, and file2.xlsx with two worksheets having charts. The merged file should be file3.xlsx with 5 sheets having 3 from file1 and 2 from file 2.

    Appreciate your inputs and thanks in advance



  24. Hi Logesh I need a java program to compare to identical excel sheet and bring a mismatches in the form of either pdf or simple HTML report.Please guide me or share sample code. Thank you in Advance

  25. Hi Lokesh,
    Sometimes the data exceeds 30 lakh rows. In such cases, can u suggest me something that split the dat into multiple excel files, zip it and give the user a downloadable zip file option? Im using Rest services by the way

  26. For me, work only with poi-ooxml in maven dependency. Otherwise xssf missing, but still very helpful article, thanks for it.

  27. Hi Lokesh,

    Great article, Really helping a lot!!

    I have written the data to the xls (Testing.xlsx), the program runs successfully but where can i get the output? (the xls file?)

  28. Hi Lokesh,

    My requirement is to insert the Excel sheet to a column in Oracle DataBase and process the files using a scheduler.
    Inserted the Excel to CLOB column.But the way it is inserted i dont feel itis the correct way.
    Even while trying to convert the CLOBData to HSSFworkbook , i am facing the below issue.

    java.io.IOException: Invalid header signature; read 0x80E21193C59380E2, expected 0xE11AB1A1E011CFD0

    Please , help me out.
    I have no idea how to resolve this.

  29. Hi Lokesh,

    I’m getting follwing error i’m followed u r code to create .xlsx file can you give any idea why this error occuring

    ReadWriteExcelFile.java:7: cannot a
    ccess org.apache.poi.hssf.usermodel.HSSFCell
    bad class file: ….\java_lib\poi-3.9-20121203.jar(org/apache/poi/hssf
    class file has wrong version 49.0, should be 48.0
    Please remove or make sure it appears in the correct subdirectory of the classpa
    import org.apache.poi.hssf.usermodel.HSSFCell;
    1 error

    can any one knows the solution for above error can you please update me in below email id:- pv_srinivas2005@yahoo.com

    • 49.0 and 48.0 are the version number of the class file format. The error message means that POI-3.9 was compiled to JDK 5 class file format and you tried to use it with JDK 4. Of course, JDK 4 couldn’t support JDK 5 class file format. I think you can try older version POI. Or just use JDK 5.
      Major version number of the class file format being used:

      J2SE 7 = 51 (0x33 hex)
      J2SE 6.0 = 50 (0x32 hex)
      J2SE 5.0 = 49 (0x31 hex)
      JDK 1.4 = 48 (0x30 hex)
      JDK 1.3 = 47 (0x2F hex)
      JDK 1.2 = 46 (0x2E hex)
      JDK 1.1 = 45 (0x2D hex)

  30. XLSX supports only 1 lakh data to be populated per sheet. Extra logic needs to be done for checking this and create new sheets depending on the volume of data fetched. this part seems to be missing in the code.

  31. Am having the following error with yourcode which i had taken reading of excel sheet . In switch condition am getting error saying that cannot resolved

    • here is my Contact Vcf File Code.
      private void getVcardString() throws IOException {

      final String vfile = “contacts.vcf”;
      // TODO Auto-generated method stub
      vCard = new ArrayList();
      cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
      int i;
      String storage_path = Environment.getExternalStorageDirectory().toString() + File.separator + vfile;
      FileOutputStream mFileOutputStream = new FileOutputStream(storage_path, false);
      for(i = 0;i<cursor.getCount();i++)
      Log.d("TAG", "Contact "+(i+1)+"VcF String is"+vCard.get(i));
      Log.d("TAG", "No Contacts in Your Phone");
      private void get(Cursor cursor2) {
      String lookupKey = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
      Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_VCARD_URI, lookupKey);
      AssetFileDescriptor fd;
      try {
      fd = this.getContentResolver().openAssetFileDescriptor(uri, "r");

      FileInputStream fis = fd.createInputStream();
      byte[] buf = new byte[(int) fd.getDeclaredLength()];
      String vcardstring= new String(buf);
      } catch (Exception e1)
      // TODO Auto-generated catch block

  32. when i am rewriting a in excel sheet at the ending of excel sheet it is deleting all my privious data and showing new data from rownum where i started writing. I can read excel and save in temp file and rewrite it, but i want any alternative way for only wrting from where i want to write

  33. HI,
    when i included all the jar files and then tried to read excel sheet,when i tried to run the application i am getting error like :
    trouble writing output: Too many methods: 66024; max is 65536. By package:
    13 java.lang
    1 java.lang.reflect
    5 java.util
    1 javax.xml.namespace
    66 org.apache.xmlbeans………………………………………..[2014-03-07 11:11:13 – exceldemo] Conversion to Dalvik format failed with error 2
    please any one help me how to clear this error.

  34. Hi, Lokesh

    I got below exception when I run a file.

    Link of the file: ISOCountryCodes081507.xls


    org.apache.poi.POIXMLException: org.apache.poi.openxml4j.exceptions.InvalidFormatException: Package should contain a content type part [M1.13]
    at org.apache.poi.util.PackageHelper.open(PackageHelper.java:41)
    at org.apache.poi.xssf.usermodel.XSSFWorkbook.(XSSFWorkbook.java:204)
    at com.howtodoinjava.demo.poi.ReadExcelDemo.main(ReadExcelDemo.java:22)
    Caused by: org.apache.poi.openxml4j.exceptions.InvalidFormatException: Package should contain a content type part [M1.13]
    at org.apache.poi.openxml4j.opc.ZipPackage.getPartsImpl(ZipPackage.java:178)
    at org.apache.poi.openxml4j.opc.OPCPackage.getParts(OPCPackage.java:662)
    at org.apache.poi.openxml4j.opc.OPCPackage.open(OPCPackage.java:269)
    at org.apache.poi.util.PackageHelper.open(PackageHelper.java:39)
    … 2 more

    • Hi Lokesh,
      I’m trying your code to experiment and getting an error at the line below:

      data.put(“1”, new Object[] {“ID”, “NAME”, “LASTNAME”}); <—Syntax error on tocken(s), misplaced construct(s)


      • Issue resolved. I created a new project in Eclipse, added the POI (jar) to the libraries and the syntax is no longer displayed. Regards,

  35. Hi Lokesh,

    when am trying to do the export excel sheet, i have to show the 5 digit zip code in xl, in java if i read it as integer for zipcode in excel sheet it is just showing it as 4 digit ex for 01201 ->1201 in xl. so if i change it as string in code, in excel sheet it is showing the error. any suggetions plz…

  36. Hi Lokesh

    I was trying
    FileInputStream file = new FileInputStream(new File(xlsPath));
    XSSFWorkbook workBook = new XSSFWorkbook(file);
    but in second line it is going in to hung state>

    Can you help me why it is going in to hung state


  37. Nice. Covered almost everything about excel… Tried reading data from excel file using POI. Smaller files works fine. But when I tried opening an excel file having 25000 rows(28 columns), out of memory exception occurred. Tired allocating maximum heap memory, still exception happens. Could you please tell me if any alternatives are available?

  38. I am trying parse values thru excel sheet to java thru readexcel, once the read file ,i want write some column in same readexcel
    how to do that

  39. Hi Lokesh, my case study is how to get data from the excel file into values of the attributes of java objects (the goal is making many objects that get values from the excel file). How can we save the values and then assign its to the attributes of objects? For instance in the excel file, we have “Name” column with values “ABC”, “DEF”,”XYZ” ; and “Age” column with values “18”, “17”, “19” corresponding; the job is making 3 objects with name and age corresponding.
    Could you show me the steps to solve it!
    Thank so much!

      • Yes, I used jexcelapi library to get data from excel file, but I dont know how to assign the values to objects. I think I have to use ArrayList to store them. just research at that. Thanks for reply!

  40. Hi,Thanks for the tutorial.
    Kindly tell me how to check for not null fields while importing data from an excel into a table ?.

  41. hi, my data displayed from the excel arent showing in their proper columns. its either out of the columns or goes into another column. for example, the headings for the columns are ‘no. of sensor for chn1’ & multiplexer. the data in those columns arent displaying properly. any suggestions on how to display them in place ? =]

  42. Hi Lokesh, with your first tutorial in writing data into excel, it returns an error:

    Exception in thread “main” java.lang.NoClassDefFoundError: org/apache/xmlbeans/XmlObject
    at com.howtodoinjava.demo.poi.WriteExcelDemo.main(WriteExcelDemo.java:19)
    Caused by: java.lang.ClassNotFoundException: org.apache.xmlbeans.XmlObject
    at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
    … 1 more

    I’ve imported all the needed jars. Please help me with this. Thank you so much! 🙂

  43. Hi Lokesh,

    I have a simple problem i guess. I am within 2 stage “For loop”. First loop is for col and second loop is for row, such that program will write “Hello” in 3 columns consecutively each with 10 rows in excel

    Can you please help me using poi packages.

    for(int i=0; i<=2; i++){ //For Col for(int j=0; j<=9; j++){ //For Rows System.out.println("Hello"); } } Thanks

  44. You colud write what import to files or give more visible information that ur example has source code 😀
    thx a lot

  45. Hi,

    I am getting errors at Iterator cellIterator = row.cellIterator(); and
    Iterator rowIterator = sheet.iterator();

    The error says Type Mismatch:cannot convert from Iterator to Iterator. What might be the problem?

  46. hey, i have these sets of data i am streaming wirelessly and i have followed your steps to create a database. i was wondering, is it possible for the data to keep refreshing itself as new data are being fetched ?

    • I really doubt that any database would be capable of doing that. At least I am not aware of any such capability. You can write another thread which keep reading data from source and write it to database.

  47. hi, what if i want to read from an csv file ? isit possible ? and how do make it read row by row ? are delays possible just like c programming ? any help would be greatly appreciated. =]

  48. hi. i was wondering if you could tell me how to display single lines at a time from an excel file. lets say im streaming data and i want the data to appear one at a time and not everything at one go. is there any delay function like C programming ? help will be much appreciated ! =]

    • I am not aware of any delay like feature in java. The most closely related feature is asynchronous operations.
      Regarding your problem, I do not fully understand your problem. But, from what I understood, you can use a queue, where you push bytes into the queue and a running thread pulls desired number of bytes( or available bytes if less bytes are present in queue at moment) and display them on screen.

  49. While searching for my problem I came across your post. I know it’s a bit late but I am sure it will be useful for the other guys…. I came across great Java Excel component by the name of Aspose.Cells for Java. It is not open source, but contains very powerful features. It allows Java developers to embed the ability to read, write and manipulate Excel® spreadsheets (XLS, XLSX, XLSM, SpreadsheetML, CSV) EML, HTML, PDF and image file formats into their own Java applications. Some Examples with code are:
    I am sure it can help

  50. Hi sir,I want to read an excel file having checkboxes and combo boxes,is it possible to do it in java sir.plz help me sir.Thanks

    Venkata Sriram

  51. A good tutorial for beginners to understand and grasp the concepts quickly.
    I have a doubt, more like a requirement and I’d appreciate if you could just suggest me how to go about doing it.

    I need to dynamically retrieve data from MySql database and then write it to an Excel file. How do I go about achieving this? Thanks in advance.

  52. The list of Jar that mentioned that need to include are total 10.8MB. That is really to huge if want to allow user to download application via internet.

    You also having the same issue? Any other suggestion?

    • Yes, I have worked on such project which was basically a desktop application. Total project size with jars was 17.8 MB. But after creating exe for that project, size reduced to 7.5 MB which is quite “OK” to me.

  53. Hi Lokesh,

    I have huge number of records in one excel as repository.
    i need to search particular record.If i go with cell by cell it takes lot of time .
    EX:if 1000 lines are there in excel if record is in 1000 line then it has to go 999 cells .
    I want to know is there any smart search is there in POI instead of every cell it should search that cell directly (as we search like from CNTRL+F)

  54. Really very very thankful…I have just 1+ yrs of experience in java…this blog has everything which I need….i mean where there are chances of stuck….

  55. hi Lokesh,

    I have a issue with excel. I have column with a date values which are taken as decimal and through dbunit the values are saving into db. While entering the values in the template if the green triangle is not coming it doesnt read those values as text i think that is feature of excel. My issue is if suppose i enter 20130630 in date column and without that triangle apperance in excel than in the db it is getting stored in exponential format like 2.01306E7 which i dont want as there are procedures written which validate the date values. Now if i do something like setting first cell type as string and then setting string value then it is throwing illegal state exception. Please suggest what needs to be done in such case.

  56. Hi Gupta,

    I have a array of formula in excel, which works fine in excel but the same thing is not working in APACHE POI…

    Could you please let us know, is there any work around to solve the issue.


      • Thanks for the quick reply, am using Xlsx verison and poi 3.8 version and here is the formula, which we are trying to execute from poi. but it’s not working..i looked at the apache poi site where they are saying array of formula not supported by poi.. is there any alternative way to modify the formula to work with POI.

        Please through the light.


  57. i am having one query. In excel if i type 8 then its reading as 8.0, but i dont want to read as 8.0 so i did this
    if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC){
    //value = (cell.getNumericCellValue() + “”).trim();
    value = (cell.getStringCellValue() + “”).trim();
    now its coming as 8, after that code. But if i insert 8.0 in excel i want output as 8.0 but i am getting as 8. How to solve this problem?

  58. Hi, thks for the tutorial,
    Got a question, when I’m about to write 40 thousand lines in the Map, by the way Im using a LinkedHashMap; Java return an Exception in thread “main” java.lang.OutOfMemoryError: GC overhead limit exceeded;
    Could you hep me with this issue, what can I do??
    Its supossed that i should write around 150 thousand lines.. it work very well under the 40 thousand lines…. the it crush.. please help me..

    • You need to write the lines in bunch. Say in bunch of 5000 lines. Once you write 5000 lines, flush in file system. Do it in loop. POI is not memory effective. I also faced such problem once. I ended up doing what i suggested you.

      • Hello again.. Ive already use the flush o 5000 lines and still got an error of memory, this time is “main” java.lang.OutOfMemoryError: Java heap space….. a this time it only write till 20000 lines in the file, Could you help me with this?
        Im using the follow code:

        int rownum = 0;
        while (rownum < f) { if(cp==5000){ System.gc(); out.flush(); Runtime.getRuntime().gc(); Thread.sleep(100000); cp = 0; } while(ct<100){ Row row = sheet.createRow(rownum++); fT++; ct++; cp++; System.out.println(rownum); Object [] objArr = data.get(String.valueOf(rownum)); int cellnum = 0; for (Object obj : objArr) { Cell cell = row.createCell(cellnum++); System.out.println(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); } } workbook.write(out); System.out.println("lineas= "+rownum); System.out.println("Excel escrito con exito.."); ct=0; System.gc(); out.flush(); Runtime.getRuntime().gc(); } System.out.println("lineas= "+fT); System.out.println("Excel escrito con exito.."); //workbook.write(out); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } by the way f = 140000 Waiting for your answer thks

  59. Hello, I’m trying to write some data to existing workbook using following code:
    OPCPackage pkg = OPCPackage.open(file);
    XSSFWorkbook workbook = new XSSFWorkbook(pkg);
    // adding rows and cells here
    No exceptions are thrown but target file always stays untouched. “Last modified” date of file changes correctly though. I wonder if I’m doing something wrong.

  60. hello sir , i am chinmay narwane ,i have a project in which i have to take data from one excel sheet to another and again i have to populate the excel sheets on runtime ,i mean for manual data enrty also the user shoul see a excell sheet how to do that

  61. Hi sir,

    Iam using POI for Generating excel,but the data comming from Oracle DB,how many rows are there that many times hashmap is filling,sometimes iam getting huge data from DB,it wont effect any performance of the Application na sir?because new Object[] creating = size of resultset. or we have to explicitly derefer the Map.can you please help me out sir.Please clear that object array creation is a good practice or not sir.?please correct me if iam wrong


    • Hi Sri, I have faced such problem in past and yes , memory problems occurs frequently when working with POI. Memory problems will not be on HashMap or java objects side, but on POI sheet and cell sides.

      So, to avoid such memory issues, initialize the program with bigger JVM memory. Second thing is to write data periodically (flush) in filesystem, rather than populating whole sheet and then write it to filesystem.

      That’s all.

  62. Hi, I need one help.
    I need to generate a word document dynamically in JAVA. Based on the input from user in the UI, the values will come from database and then, i need to generate the values in word doc with proper formatting like bold, italic and font-size. The word document will contain proper header & footer, page numbers with some images(if possible). This same thing i need to generate a PDF also.

    Thanks in advance!

  63. Exception in thread “main” java.lang.NoClassDefFoundError: org/apache/xmlbeans/XmlObject
    at Excel_Final.main(Excel_Final.java:49)
    Caused by: java.lang.ClassNotFoundException: org.apache.xmlbeans.XmlObject

    Now I am facing this error after clearing the Iterator Issues.
    Do I need to import any necessary packages? Please help me.

  64. Iterator rowIterator = sheet.iterator();
    while(rowIterator.hasNext()) {
    Row row = rowIterator.next();

    while attempting to Iterate in Cells, I am facing “The Type HTML Document.Iterator is not generic. It can not be parameterized with Arguments ”
    I dont have any clue why i am facing this prob. Can you help me to sort out this…?

  65. Thanks sir,i have one doubt sir,How to make only Headers bold by adding directly to map and iterate sir.

Comments are closed.


A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.