Java apache poi excel формула

I am currently using Apache POI for Java to set formulas in cells.

But after I run the program and open the Excel file that I created and processed, the cells with the formula include the formula as a string, rather than the value the formula should have returned.

Jasper's user avatar

Jasper

2,1463 gold badges33 silver badges50 bronze badges

asked Feb 26, 2010 at 3:02

vamsi's user avatar

5

The HSSFCell object has methods .setCellType and .setCellFormula which you need to call like this:

// "cell" object previously created or looked up
String strFormula= "SUM(A1:A10)";
cell.setCellType(HSSFCell.CELL_TYPE_FORMULA);
cell.setCellFormula(strFormula);

Daya's user avatar

Daya

7243 gold badges14 silver badges32 bronze badges

answered Feb 26, 2010 at 3:07

5

Cell Constants are deprecated and will be removed from version 4.0
instead of Cell Use

CellType.FORMULA

String formula= "SUM(B4:B20)";
cell.setCellType(CellType.FORMULA);
cell.setCellFormula(formula);

UPDATE

setCellType() :Based on @fenix comment. This method is deprecated and will be removed in POI 5.0. Use explicit setCellFormula(String), setCellValue(…) or setBlank() to get the desired result.

String formula= "SUM(B4:B20)";
cell.setCellFormula(formula);

answered Apr 26, 2017 at 12:31

Jinu P C's user avatar

Jinu P CJinu P C

3,0761 gold badge20 silver badges28 bronze badges

2

The below code worked fine for me, hope this could be useful to someone.

cell.setCellType(Cell.CELL_TYPE_FORMULA);
cell.setCellFormula("SUM(C70:C76)");

sth's user avatar

sth

220k53 gold badges279 silver badges365 bronze badges

answered Feb 18, 2013 at 11:12

user1901203's user avatar

0

Apache POI does not support user-defined functions.

From the documentation:

Note that user-defined functions are not supported, and is not likely
to done any time soon… at least, not till there is a VB
implementation in Java!

answered Nov 26, 2012 at 7:51

filsa's user avatar

filsafilsa

1,6463 gold badges15 silver badges16 bronze badges

You could use this to evaluate the formulas in the workbook:

        // Evaluate all formulas in the sheet, to update their value
    FormulaEvaluator formulaEvaluator = workbook.getCreationHelper().createFormulaEvaluator();
    formulaEvaluator.evaluateAll();

answered Aug 13, 2018 at 14:35

Diogo Vilela's user avatar

I was having the similar problem and "SUM(B4:B20)" does not work for me directly as the sheet was generated dynamically. The problem was with the cell reference.

On the basis of https://stackoverflow.com/a/2339262/2437655 and https://stackoverflow.com/a/33098060/2437655 I was able to generate the actual formula. e.g.

 val totalProductQtyPerUserCell = userDetailsRow.createCell(products.size + 1)
 totalProductQtyPerUserCell.cellType = HSSFCell.CELL_TYPE_FORMULA
 totalProductQtyPerUserCell.cellFormula = "SUM(${CellReference.convertNumToColString(1)}${totalProductQtyPerUserCell.row.rowNum + 1}:${CellReference.convertNumToColString(products.size)}${totalProductQtyPerUserCell.row.rowNum + 1})"

Hope that help.

answered Jun 17, 2018 at 20:41

Shubham AgaRwal's user avatar

Shubham AgaRwalShubham AgaRwal

4,2248 gold badges39 silver badges60 bronze badges

Here is one suggested way:

Workbook workbook1 = new SXSSFWorkbook(-1);
Sheet newSheet = workbook1.createSheet("Valuations");
Row newRow = newSheet.createRow(i-1);
newRow.createCell(L++).setCellFormula("AVERAGE(" + "E" + i + ":" + "G" + i + ")");

Where E and G are the columns like A1,B1,C1….E1…G1
and i represent a number in the above Column.

L++ is simply an incremental counter.

answered Jan 10, 2020 at 20:03

prashant.kr.mod's user avatar

In the previous article, we have seen how to read data from the formula cell, here we are going to create the formula cell using Apache POI.

In this article, we are creating an Excel file with three columns consisting of values and the last column is the formula cell which is calculated from the other cells by defining a certain formula, here we are creating the formula cell by adding all other data in the cells.

Pre-requisites:

To work will these, we needed the following software in your systems.

  • Make sure your system has Java, if not download the latest java SDK version here.
  • Create the Maven project.

For creating the maven project refer to this article on how to create a selenium maven project with eclipse.

  • Add the Apache POI dependency into the POM.xml file

Program for creating Formula cell in Excel using Apache POI: 

Java

package GFG_Maven.GFG_MAven;

import org.testng.annotations.Test;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import org.apache.poi.xssf.usermodel.XSSFCell;

import org.apache.poi.xssf.usermodel.XSSFRow;

import org.apache.poi.xssf.usermodel.XSSFSheet;

import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class Geeks {

    @Test

    public void geekforgeeks() throws IOException{

        XSSFWorkbook workbook=new XSSFWorkbook();

        XSSFSheet sheet=workbook.createSheet("Numbers");

        XSSFRow row=sheet.createRow(0);

        row.createCell(0).setCellValue(10);

        row.createCell(1).setCellValue(10);

        row.createCell(2).setCellValue(10);

        row.createCell(3).setCellFormula("A1+B1+C1");

        FileOutputStream file = new FileOutputStream("C:\Users\ADMIN\Desktop\calc.xlsx");

        workbook.write(file);

        file.close();

        System.out.println("calc.xlsx file is created with Formula cell");

    }

}

Code Explanation:

After creating the workbook, we have created the sheet in the workbook as “Numbers”.

XSSFSheet sheet=workbook.createSheet(“Numbers”)

Then we have created the first row in that sheet by the createRow() method.

XSSFRow row=sheet.createRow(0);

After that, we have created the cells in the first row by row.createCell(cell number).setCellValue(value);

row.createCell(0).setCellValue(10);

Now, in the fourth cell, we are using the formula to calculate the cell value by using the setCellFormula(formula).

row.createCell(3).setCellFormula(“A1+B1+C1”);

In the end, we are going to write the values into the Excel sheet by creating a file output stream into the defined location 

FileOutputStream file = new FileOutputStream(“specify the location for creating the file”);

Writing the cell values into the file by workbook.write(file), 

Output:

After we run the code, we get the output and the Excel files are created.

Now we can notice that the Excel file is created in the defined location. I have given desktop location, so the file is created on my desktop

If you open the Excel file the cell values are created in the sheet with the formula cell.

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 software for the HR or Finance domain, there is usually a requirement for generating excel reports 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.

This Apache POI tutorial will discuss some everyday excel operations in real-life applications.

  1. 1. Maven Dependency
  2. 2. Important Classes in POI Library
  3. 3. Writing an Excel File
  4. 4. Reading an Excel File
  5. 5. Add and Evaluate Formula Cells
  6. 6. Formatting the Cells
  7. 7. Conclusion

1. Maven Dependency

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

<dependency>
  <groupId>org.apache.poi</groupId>
  <artifactId>poi</artifactId>
  <version>5.2.2</version>
</dependency>

<dependency>
  <groupId>org.apache.poi</groupId>
  <artifactId>poi-ooxml</artifactId>
  <version>5.2.2</version>
</dependency>

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 huge 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 within a sliding window, while XSSF gives access to all rows in the document.
  2. Row and Cell

    Apart from the above classes, Row and Cell interact with a particular row and a particular cell in an 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 to a sheet, primarily based on some rules.

  4. FormulaEvaluator

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

3. Writing an Excel File

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

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

  1. Create a workbook
  2. Create a sheet in workbook
  3. Create a row in sheet
  4. Add cells to sheet
  5. Repeat steps 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)
                    cell.setCellValue((String)obj);
                else if(obj instanceof Integer)
                    cell.setCellValue((Integer)obj);
            }
        }
        try
        {
            //Write the workbook in file system
            FileOutputStream out = new FileOutputStream(new File("howtodoinjava_demo.xlsx"));
            workbook.write(out);
            out.close();
            System.out.println("howtodoinjava_demo.xlsx written successfully on disk.");
        } 
        catch (Exception e) 
        {
            e.printStackTrace();
        }
    }
}
poi-demo-write-file

See Also: Appending Rows to Excel

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 an excel sheet
  2. Get to the desired sheet
  3. Increment row number
  4. iterate over all cells in a row
  5. repeat steps 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) 
    {
        try
        {
            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");
                            break;
                        case Cell.CELL_TYPE_STRING:
                            System.out.print(cell.getStringCellValue() + "t");
                            break;
                    }
                }
                System.out.println("");
            }
            file.close();
        } 
        catch (Exception e) 
        {
            e.printStackTrace();
        }
    }
}

Program Output:

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

See Also: Apache POI – Read an Excel File using SAX Parser

5. Add and Evaluate Formula Cells

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

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

The sheet has four cells in a row and the fourth one in the multiplication of all the 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(0).setCellValue("Pricipal");
    header.createCell(1).setCellValue("RoI");
    header.createCell(2).setCellValue("T");
    header.createCell(3).setCellValue("Interest (P r t)");
      
    Row dataRow = sheet.createRow(1);
    dataRow.createCell(0).setCellValue(14500d);
    dataRow.createCell(1).setCellValue(9.25);
    dataRow.createCell(2).setCellValue(3d);
    dataRow.createCell(3).setCellFormula("A2*B2*C2");
      
    try {
        FileOutputStream out =  new FileOutputStream(new File("formulaDemo.xlsx"));
        workbook.write(out);
        out.close();
        System.out.println("Excel with foumula cells written successfully");
          
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

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()
{
    try
    {
        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");
                        break;
                    case Cell.CELL_TYPE_STRING:
                        System.out.print(cell.getStringCellValue() + "tt");
                        break;
                    case Cell.CELL_TYPE_FORMULA:
                        //Not again
                        break;
                }
            }
            System.out.println("");
        }
        file.close();
    } 
    catch (Exception e) 
    {
        e.printStackTrace();
    }
}

Program Output:

Pricipal        RoI         T       Interest (P r t)        
14500.0         9.25        3.0     402375.0  
poi-demo-write-formula

6. Formatting the Cells

So far we have seen examples of reading/writing and excel files using Apache POI. But, when creating a report in an excel file, it is essential 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, 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 specific range

This 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
    sheet.createRow(0).createCell(0).setCellValue(84);
    sheet.createRow(1).createCell(0).setCellValue(74);
    sheet.createRow(2).createCell(0).setCellValue(50);
    sheet.createRow(3).createCell(0).setCellValue(51);
    sheet.createRow(4).createCell(0).setCellValue(49);
    sheet.createRow(5).createCell(0).setCellValue(41);
 
    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();
    fill1.setFillBackgroundColor(IndexedColors.BLUE.index);
    fill1.setFillPattern(PatternFormatting.SOLID_FOREGROUND);
 
    //Condition 2: Cell Value Is  less than      50   (Green Fill)
    ConditionalFormattingRule rule2 = sheetCF.createConditionalFormattingRule(ComparisonOperator.LT, "50");
    PatternFormatting fill2 = rule2.createPatternFormatting();
    fill2.setFillBackgroundColor(IndexedColors.GREEN.index);
    fill2.setFillPattern(PatternFormatting.SOLID_FOREGROUND);
 
    CellRangeAddress[] regions = {
            CellRangeAddress.valueOf("A1:A6")
    };
 
    sheetCF.addConditionalFormatting(regions, rule1, rule2);
}
poi-demo-formatting-1

6.2. Highlight Duplicate Values

Highlight all cells which have duplicate values in observed cells.

static void formatDuplicates(Sheet sheet) {
    sheet.createRow(0).createCell(0).setCellValue("Code");
    sheet.createRow(1).createCell(0).setCellValue(4);
    sheet.createRow(2).createCell(0).setCellValue(3);
    sheet.createRow(3).createCell(0).setCellValue(6);
    sheet.createRow(4).createCell(0).setCellValue(3);
    sheet.createRow(5).createCell(0).setCellValue(5);
    sheet.createRow(6).createCell(0).setCellValue(8);
    sheet.createRow(7).createCell(0).setCellValue(0);
    sheet.createRow(8).createCell(0).setCellValue(2);
    sheet.createRow(9).createCell(0).setCellValue(8);
    sheet.createRow(10).createCell(0).setCellValue(6);
 
    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);
    font.setFontColorIndex(IndexedColors.BLUE.index);
 
    CellRangeAddress[] regions = {
            CellRangeAddress.valueOf("A2:A11")
    };
 
    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)");
}
poi-demo-formatting-2

6.3. Alternate Color 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();
    fill1.setFillBackgroundColor(IndexedColors.LIGHT_GREEN.index);
    fill1.setFillPattern(PatternFormatting.SOLID_FOREGROUND);
 
    CellRangeAddress[] regions = {
            CellRangeAddress.valueOf("A1:Z100")
    };
 
    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)");
}
poi-demo-formatting-3

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

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

static void expiryInNext30Days(Sheet sheet) 
{
    CellStyle style = sheet.getWorkbook().createCellStyle();
    style.setDataFormat((short)BuiltinFormats.getBuiltinFormat("d-mmm"));
 
    sheet.createRow(0).createCell(0).setCellValue("Date");
    sheet.createRow(1).createCell(0).setCellFormula("TODAY()+29");
    sheet.createRow(2).createCell(0).setCellFormula("A2+1");
    sheet.createRow(3).createCell(0).setCellFormula("A3+1");
 
    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);
    font.setFontColorIndex(IndexedColors.BLUE.index);
 
    CellRangeAddress[] regions = {
            CellRangeAddress.valueOf("A2:A4")
    };
 
    sheetCF.addConditionalFormatting(regions, rule1);
 
    sheet.getRow(0).createCell(1).setCellValue("Dates within the next 30 days are highlighted");
}
poi-demo-formatting-4

I am ending this apache poi tutorial here to keep the post within a limit.

7. Conclusion

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 !!

Source Code on Github

package org.arpit.java2blog;

import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;

import java.util.ArrayList;

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;

public class WriteExcelMain {

public static void main(String[] args) throws IOException {

  writeFileUsingPOI();

}

public static void writeFileUsingPOI() throws IOException

{

  //create blank workbook

  XSSFWorkbook workbook = new XSSFWorkbook();

  //Create a blank sheet

  XSSFSheet sheet = workbook.createSheet(«Country»);

  ArrayList<Object[]> data=new ArrayList<Object[]>();

  data.add(new String[]{«Country»,«Capital»,«Population»});

  data.add(new Object[]{«India»,«Delhi»,10000});

  data.add(new Object[]{«France»,«Paris»,40000});

  data.add(new Object[]{«Germany»,«Berlin»,20000});

  data.add(new Object[]{«England»,«London»,30000});

  //Iterate over data and write to sheet

  int rownum = 0;

  for (Object[] countries : data)

  {

   Row row = sheet.createRow(rownum++);

   int cellnum = 0;

   for (Object obj : countries)

   {

    Cell cell = row.createCell(cellnum++);

    if(obj instanceof String)

     cell.setCellValue((String)obj);

    else if(obj instanceof Double)

     cell.setCellValue((Double)obj);

    else if(obj instanceof Integer)

     cell.setCellValue((Integer)obj);

   }

  }

  Row rowGap = sheet.createRow(rownum++);

  Row row = sheet.createRow(rownum++);

  Cell cellTotal = row.createCell(0);

  cellTotal.setCellValue(«Total Population»);

  // Setting cell formula and cell type

  Cell cell = row.createCell(2);

  cell.setCellFormula(«SUM(C2:C5)»);

  cell.setCellType(Cell.CELL_TYPE_FORMULA);

  try

  {

   //Write the workbook to the file system

   FileOutputStream out = new FileOutputStream(new File(«CountriesDetails.xlsx»));

   workbook.write(out);

   out.close();

   System.out.println(«CountriesDetails.xlsx has been created successfully»);

  }

  catch (Exception e)

  {

   e.printStackTrace();

  }

  finally {

   workbook.close();

  }

}

}

HOME

In the previous tutorial, I have explained How to update data in existing excel in Java. In this Java Excel tutorial, I will explain how to create an Excel with formula in a Java program. Excel is very excellent in calculating formulas. The Apache POI library provides excellent support for working with formulas in Excel.

I’m using Apache POI to write data to the excel file. To download and install Apache POI, refer here.

If you are using maven, then you need to add below dependency in pom.xml.

<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>5.0.0</version>
</dependency>
  
  
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>5.0.0</version>
</dependency>

To know about various Interfaces and Classes in Excel, please refer this link.

Below are the steps which explain how to add Formulas in Excel.

Step 1 – Create a blank workbook.

XSSFWorkbook workbook = new XSSFWorkbook();

Step 2 – Import XSSFWorkbook from package.

import org.apache.poi.xssf.usermodel.XSSFWorkbook;

Step 3 – Create a sheet and pass name of the sheet.

XSSFSheet sheet = workbook.createSheet("Calculate Salary");

Step 4 – Import XSSFSheet from package.

import org.apache.poi.xssf.usermodel.XSSFSheet;

Step 5 – Create a Row. A spreadsheet consists of rows and cells. It has a grid layout. I have created object called Header of XSSFRow.

	XSSFRow header = sheet.createRow(0);

Step 6 – Below syntax create new cells within the row at index 0 and set a string value for the cell.

header.createCell(0).setCellValue("Employee_Name");

Step 7 – Below syntax creates a cell at index 4 and sets formula for cell.

dataRow.createCell(4).setCellFormula("B2+C2+D2");

Step 8 – The following line of code sets formula for the cell at the row #1 and column #5 (remember index is 0-based):

In case the column (Cell) does not exist (but the row does), use the following code.

XSSFRow dataRow = sheet.createRow(1);
dataRow.createCell(5).setCellFormula("SUM(B2:C2)");

In the above line, note that you should make sure that the cell at position (1, 5) does exist, otherwise you get a NullPointerException.

Let us see a program where I have created a cell which contains the formula.

public class FormulaExample {

	public static void main(String[] args) {

		// Create object of XSSFWorkbook class
		XSSFWorkbook workbook = new XSSFWorkbook();

		// Create object of XSSFSheet class
		XSSFSheet sheet = workbook.createSheet("Calculate Salary");

		// Create Header row using XSSFRow class
		XSSFRow header = sheet.createRow(0);
		header.createCell(0).setCellValue("Employee_Name");
		header.createCell(1).setCellValue("Base_Salary");
		header.createCell(2).setCellValue("Variable_Pay");
		header.createCell(3).setCellValue("Other_Benefits");
		header.createCell(4).setCellValue("Total Salary");
		header.createCell(5).setCellValue("Base_Variable Salary");

		XSSFRow dataRow = sheet.createRow(1);
		dataRow.createCell(0).setCellValue("George");
		dataRow.createCell(1).setCellValue(5000);
		dataRow.createCell(2).setCellValue(650);
		dataRow.createCell(3).setCellValue(1200);

		// Set formula
		dataRow.createCell(4).setCellFormula("B2+C2+D2");
		dataRow.createCell(5).setCellFormula("SUM(B2:C2)");

		try {

			// Write the workbook in file system
			FileOutputStream out = new FileOutputStream(new File("Salary_Slip.xlsx"));
			workbook.write(out);
			out.close();
			System.out.println("Excel written successfully.");

		} catch (IOException e) {
			e.printStackTrace();

		}
	}
}

That’s it! Well Done! Cheers!!

Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!

В прошлых двух статьях мы познакомились с библиотекой Apache POI, а также разобрались со считыванием данных из Excel документов в форматах .xls и .xlsx. Сегодня мы продолжим изучение возможностей этой библиотеки и попробуем создать новый Excel файл с формулами и стилями. Скачать проект Вы сможете в конце статьи.

Если Вы еще не знакомы с Apache POI, то рекомендую вкратце ознакомится с ее возможностями и способами ее подключения в проект по этой ссылке.

Внимание, код не очень красив и оптимизирован. Я хотел просто продемонстрировать возможности этой удобной библиотеки.

Для начала давайте создадим простой xls файл и запишем в него какие-то данные. А далее будем применять к нему стили и добавлять формулы.

Для удобной работы с данными нам потребуется дополнительный класс, который будет представлять собой модель данных, которую мы будем записывать в файл:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

package ua.com.prologistic.model;

public class DataModel {

    private String name;

    private String surname;

    private String city;

    private Double salary;

    public DataModel() {

    }

    public DataModel(String name, String surname, String city, Double salary) {

        this.name = name;

        this.surname = surname;

        this.city = city;

        this.salary = salary;

    }

    public String getName() {

        return name;

    }

    public void setName(String name) {

        this.name = name;

    }

    public String getSurname() {

        return surname;

    }

    public void setSurname(String surname) {

        this.surname = surname;

    }

    public String getCity() {

        return city;

    }

    public void setCity(String city) {

        this.city = city;

    }

    public Double getSalary() {

        return salary;

    }

    public void setSalary(Double salary) {

        this.salary = salary;

    }

}

Как видим, это простой класс с полями для имени, фамилии, города и зарплаты какого-то человека.

Ниже представлен листинг класса, в котором создается сам Excel файл:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

package ua.com.prologistic.excel;

import org.apache.poi.hssf.usermodel.HSSFSheet;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import org.apache.poi.ss.usermodel.Row;

import ua.com.prologistic.model.DataModel;

import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;

import java.text.ParseException;

import java.util.ArrayList;

import java.util.List;

public class ExcelWorker {

    public static void main(String[] args) throws ParseException {

        // создание самого excel файла в памяти

        HSSFWorkbook workbook = new HSSFWorkbook();

        // создание листа с названием «Просто лист»

        HSSFSheet sheet = workbook.createSheet(«Просто лист»);

        // заполняем список какими-то данными

        List<DataModel> dataList = fillData();

        // счетчик для строк

        int rowNum = 0;

        // создаем подписи к столбцам (это будет первая строчка в листе Excel файла)

        Row row = sheet.createRow(rowNum);

        row.createCell(0).setCellValue(«Имя»);

        row.createCell(1).setCellValue(«Фамилия»);

        row.createCell(2).setCellValue(«Город»);

        row.createCell(3).setCellValue(«Зарплата»);

        // заполняем лист данными

        for (DataModel dataModel : dataList) {

            createSheetHeader(sheet, ++rowNum, dataModel);

        }

        // записываем созданный в памяти Excel документ в файл

        try (FileOutputStream out = new FileOutputStream(new File(«F:\Apache POI Excel File.xls»))) {

            workbook.write(out);

        } catch (IOException e) {

            e.printStackTrace();

        }

        System.out.println(«Excel файл успешно создан!»);

    }

    // заполнение строки (rowNum) определенного листа (sheet)

    // данными  из dataModel созданного в памяти Excel файла

    private static void createSheetHeader(HSSFSheet sheet, int rowNum, DataModel dataModel) {

        Row row = sheet.createRow(rowNum);

        row.createCell(0).setCellValue(dataModel.getName());

        row.createCell(1).setCellValue(dataModel.getSurname());

        row.createCell(2).setCellValue(dataModel.getCity());

        row.createCell(3).setCellValue(dataModel.getSalary());

    }

    // заполняем список рандомными данными

    // в реальных приложениях данные будут из БД или интернета

    private static List<DataModel> fillData() {

        List<DataModel> dataModels = new ArrayList<>();

        dataModels.add(new DataModel(«Howard», «Wolowitz», «Massachusetts», 90000.0));

        dataModels.add(new DataModel(«Leonard», «Hofstadter», «Massachusetts», 95000.0));

        dataModels.add(new DataModel(«Sheldon», «Cooper», «Massachusetts», 120000.0));

        return dataModels;

    }

}

Обратите внимание, что мы использовали try with resources — одну из особенностей Java 7. А это значит, что нам не нужно беспокоится о закрытии файла вручную. В Java 7 конструкцию try-catch-finally можно не использовать, так как ей на смену пришла try with resources, которая сама закрывает открытые файлы или потоки без вашего вмешательства.

После запуска приведенной выше программы, в корне проекта создастся файл с названием Apache POI Excel File.xls. Давайте посмотрим на его содержимое:

Apache POI Excel File.xls

Лист Excel файла называется «Просто лист», как мы и называли, а данные расположены правильно.

Добавление стилей в Excel документ на Java

Теперь давайте поупражняемся с обновлением файла, а именно добавлением стилей. Например, выделим имя столбцов из первой строки жирным.

Для этого нам понадобится еще один метод setBoldStyle():

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

private static void setBoldStyle() throws IOException {

        // получаем файл с диска

        FileInputStream file = new FileInputStream(new File(«F:\Apache POI Excel File.xls»));

        // считываем его в память

        HSSFWorkbook workbook = new HSSFWorkbook(file);

        // говорим, что хотим работать с первым листом

        HSSFSheet sheet = workbook.getSheetAt(0);

        // создаем шрифт

        HSSFFont font = workbook.createFont();

        // указываем, что хотим его видеть жирным

        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);

        // создаем стиль для ячейки

        HSSFCellStyle style = workbook.createCellStyle();

        // и применяем к этому стилю жирный шрифт

        style.setFont(font);

        // получаем первую строку листа excel файла

        Row row = sheet.getRow(0);

        // проходим по всем ячейкам этой строки

        for (int i = 0; i < row.getPhysicalNumberOfCells(); i++) {

            // применяем созданный выше стиль к каждой ячейке

            row.getCell(i).setCellStyle(style);

        }

        // получаем доступ к excel файлу и обновляем его

        try (FileOutputStream out = new FileOutputStream(new File(«F:\Apache POI Excel File.xls»))) {

            workbook.write(out);

        } catch (IOException e) {

            e.printStackTrace();

        }

        System.out.println(«Excel файл успешно обновлен!»);

    }

Как видите, мы просто обходим все ячейки первой строки и применяем к ней стиль BOLD.

Результат выполнения этого кода представлен ниже:

excel file updated

С помощью Apache POI это делается быстро и удобно.

Добавление формул в Excel документ на Java

Теперь попробуем разобраться с добавлением формул с помощью Apache POI.

Apache POI не позволяет устанавливать в ячейки значения из знаком равно: «=».

Пример:

Можно делать так:

cell.setCellFormula(«D2+D3+D4»);

и вот так:

cell.setCellFormula(«SUM(D2:D4)»);

Но если Вы попробуете написать так:

cell.setCellFormula(«=D2*D3*D4»);

то вылетит exception с сообщением о недопустимой операции. Apache POI не позволяет работать с формулами таким образом.

И так, в теории мы подкованы, теперь добавим простую формулу. Для этого напишем еще один метод setFormula():

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

private static void setFormula() throws IOException {

        // получаем файл с диска

        FileInputStream file = new FileInputStream(new File(«F:\Apache POI Excel File.xls»));

        // считываем его в память

        HSSFWorkbook workbook = new HSSFWorkbook(file);

        // говорим, что хотим работать с первым листом

        HSSFSheet sheet = workbook.getSheetAt(0);

        // создаем 5ю строку листа excel файла

        // (сейчас она null, так как в ней нет никаких данных)

        Row row = sheet.createRow(4);

        // идем в 4ю ячейку строки и устанавливаем

        // формулу подсчета зарплат (столбец D)

        Cell sum = row.createCell(3);

        sum.setCellFormula(«D2+D3+D4»);

        // создаем шрифт

        HSSFFont font = workbook.createFont();

        // указываем, что хотим его видеть красным

        font.setColor(Font.COLOR_RED);

        // создаем стиль для ячейки

        HSSFCellStyle style = workbook.createCellStyle();

        // и применяем к этому стилю жирный шрифт

        style.setFont(font);

        sum.setCellStyle(style);

        // получаем доступ к excel файлу и обновляем его

        try (FileOutputStream out = new FileOutputStream(new File(«F:\Apache POI Excel File.xls»))) {

            workbook.write(out);

        } catch (IOException e) {

            e.printStackTrace();

        }

        System.out.println(«Excel файл успешно обновлен!»);

    }

В нем мы открываем файл, добавляем к нему еще одну строку с ячейкой для подсчета суммы зарплаты физиков. И да, выделяем ее красным цветом.

Результат выполнения представленного выше метода:

excel file updated with formula

Урок по созданию нового Excel файла в Java с помощью Apache POI подошел к концу. Скачать рабочий проект можно по этой ссылке.

Подробнее о считывании Excel файлов Вы найдете здесь.

Подписывайтесь на обновления и получайте новые уроки по Java и Android сразу на почту!

Понравилась статья? Поделить с друзьями:
  • Java apache poi excel примеры
  • Java and word document
  • Java and read excel file
  • Java and excel files
  • Java and excel examples