Write to Excel File in Java Using Apache POI

In this article we’ll see how to write to Excel file in Java using Apache POI library. If you have to read an Excel file in Java you can check this post- Read Excel File in Java Using Apache POI

Apache POI

Apache POI is a Java API for Microsoft documents. Using Apache POI you can read and write MS Excel files using Java. In addition, you can read and write MS Word and MS PowerPoint files using Java.

Apache POI provides support for reading both OLE2 files and Office Open XML standards (OOXML) files.

  • OLE2 files include most Microsoft Office files such as XLS, DOC, and PPT as well as MFC serialization API based file formats.
  • Office OpenXML Format is the new standards based XML file format found in Microsoft Office 2007 and 2008. This includes XLSX, DOCX and PPTX.

Which means Apache POI supports writing excel files having .xls format as well as excel files with .xlsx format.

Maven dependencies for Apache POI

To write to excel file using Apache POI you need to add the following dependency.

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

This dependency adds the following jars-

poi-ooxml-4.0.1.jar
poi-4.0.1.jar
poi-ooxml-schemas-4.0.1.jar
curvesapi-1.05.jar
commons-compress-1.18.jar
commons-math3-3.6.1.jar
commons-collections4-4.2.jar
xmlbeans-3.0.2.jar

Here note that poi-4.0.1.jar has classes for working with old excel format (.xls)
and poi-ooxml-4.0.1.jar has classes for working with newer excel format (.xlsx). Apache POI 4.0.1 requires Java 8 or newer.

Apache POI classes for writing excel files

Following section gives an overview of classes that are used for writing to excel file in Java using Apache POI.
Apache POI library provides two implementations for two excel spread sheet formats-

  • HSSF– It is the pure Java implementation for earlier excel format (.xls). Classes in this implementation will usually have HSSF prefix like HSSFWorkBook, HSSFSheet.
  • XSSF– It is the pure Java implementation for xslx file format (OOXML). Classes in this implementation will usually have XSSF prefix like XSSFWorkBook, XSSFSheet.

SS– It is a package built on top of HSSF and XSSF that provides common support for both formats with a common API. You should try to use classes from this package for better compatibility.

While working with excel file the usual progression is-

write to excel file in Java
There are interfaces corresponding to this progression-

  • org.apache.poi.ss.usermodel.Workbook– High level representation of a Excel workbook. This is the first object most users will construct whether they are reading or writing a workbook. It is also the top level object for creating new sheets.
  • org.apache.poi.ss.usermodel.Sheet– High level representation of a Excel worksheet. Sheets are the central structures within a workbook.
  • org.apache.poi.ss.usermodel.Row– High level representation of a row of a spreadsheet.
  • org.apache.poi.ss.usermodel.Cell– High level representation of a cell in a row of a spreadsheet. Cells can be numeric, formula-based or string-based (text).

For creating a Workbook, WorkbookFactory class is used.

  • org.apache.poi.ss.usermodel.WorkbookFactory– Factory for creating the appropriate kind of Workbook (be it HSSFWorkbook or XSSFWorkbook), by auto-detecting from the supplied input.

Write excel file in Java using Apache POI example

For the example there is a class Employee with fields firstName, lastName, department and DOB. Using these fields data is written to excel file in 4 columns per row.
Employee class

public class Employee {
  private String firstName;
  private String lastName;
  private String department;
  private Date dob;

  public Employee(String firstName, String lastName, String department, Date dob) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.department = department;
    this.dob = dob;
  }
  public String getFirstName() {
    return firstName;
  }
  public void setFirstName(String firstName) {
    this.firstName = firstName;
  }
  public String getLastName() {
    return lastName;
  }
  public void setLastName(String lastName) {
    this.lastName = lastName;
  }
  public String getDepartment() {
    return department;
  }
  public void setDepartment(String department) {
    this.department = department;
  }
  public Date getDob() {
    return dob;
  }
  public void setDob(Date dob) {
    this.dob = dob;
  }	

  @Override
  public String toString() {    
    return getFirstName() + " " + getLastName() + " " + getDepartment() + " " + getDob();
  }
}

Following Java class retrieve data from fields of Employee objects and write to excel sheet.

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class WriteExcel {
  private static final String EXCEL_FILE_PATH="F:\\knpcode\\Java\\Java Programs\\Java IO\\Employee.xlsx";
  public static void main(String[] args) {
    WriteExcel writeExcel = new WriteExcel();		
    writeExcel.writeExcelFile(EXCEL_FILE_PATH, WriteExcel.getEmployees());
  }
	
  public void writeExcelFile(String excelFilePath, List<Employee> employees) {
    final String[] header= {"First Name", "Last Name", "Department", "DOB"};
    Workbook workbook = null;
    // Excel with .xslx extension
    workbook = new XSSFWorkbook();
    // For .xls extension HSSF workbook can be created
    //workbook = new HSSFWorkbook();

    // Creating sheet with in the workbook
    Sheet sheet = workbook.createSheet("Employees");
    /*Font and style For Header*/
    Font font = workbook.createFont();
    font.setFontName("VERDANA");
    font.setColor(IndexedColors.CORNFLOWER_BLUE.getIndex());
    font.setBold(true);
         
    CellStyle style = workbook.createCellStyle();
    style.setFont(font);
    style.setWrapText(true);
    style.setAlignment(HorizontalAlignment.CENTER);
    style.setVerticalAlignment(VerticalAlignment.CENTER);
    style.setFillForegroundColor(IndexedColors.LIGHT_TURQUOISE.getIndex());
    style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
    style.setBorderRight(BorderStyle.THIN);
    style.setRightBorderColor(IndexedColors.BLACK.getIndex());
    style.setBorderLeft(BorderStyle.THIN);
    style.setLeftBorderColor(IndexedColors.BLACK.getIndex());
    style.setBorderTop(BorderStyle.THIN);
    style.setTopBorderColor(IndexedColors.BLACK.getIndex());
    style.setBorderBottom(BorderStyle.THIN);
    style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
         
    Row row = sheet.createRow(0);
    // Writing header to excel
    for(int i = 0; i < header.length; i++) {
       // each column 20 characters wide
       sheet.setColumnWidth(i, 20*256);
       Cell cell = row.createCell(i);
       cell.setCellValue(header[i]);
       cell.setCellStyle(style);
    }   
    // Header styling ends
    //Preparing column data for each row
    CellStyle dateStyle = workbook.createCellStyle();
    // Setting format For the date column
    dateStyle.setDataFormat(workbook.getCreationHelper()
                                    .createDataFormat().getFormat("dd/MM/yyyy"));
    int rowNum = 1;
    for(Employee emp : employees) {
      // create new row
      row = sheet.createRow(rowNum++);
      row.createCell(0).setCellValue(emp.getFirstName());
      row.createCell(1).setCellValue(emp.getLastName());
      row.createCell(2).setCellValue(emp.getDepartment());            
      Cell cell = row.createCell(3);
      cell.setCellValue(emp.getDob());
      cell.setCellStyle(dateStyle);
    }
        
    FileOutputStream outputStream = null;
    try {
     outputStream = new FileOutputStream(excelFilePath);
     // Writing to excel sheet
     workbook.write(outputStream);
    } catch (IOException exp) {
     // TODO Auto-generated catch block
     exp.printStackTrace();
    }finally {
      if(outputStream != null) {
        try {
          outputStream.close();
          workbook.close();
        } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }
    }   
  }
	
  // Method to get list of employees
  private static List<Employee> getEmployees(){
    List<Employee> employees = new ArrayList<Employee>();
    Calendar dob = Calendar.getInstance();
    // Month is 0 based
    dob.set(1990,10,12); //12-Nov-1990
    employees.add(new Employee("John", "Emerson", "Technology", dob.getTime()));
    dob.set(1960, 04, 07);
    employees.add(new Employee("Shelly", "Mcarthy", "HR", dob.getTime()));
    dob.set(1992, 02, 03);
    employees.add(new Employee("Tom", "Cevor", "Finance", dob.getTime()));
    return employees;
  }
}

Running this program creates excel sheet as shown below.

excel file in Java
Related Posts

That’s all for the topic Write to Excel File in Java Using Apache POI. If something is missing or you have something to share about the topic please write a comment.


You may also like

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.