Apache POI - Workbooks



Here the term 'Workbook' means Microsoft Excel file. After completion of this chapter, you will be able to create new Workbooks and open existing Workbooks with your Java program.

Example - Create Blank Workbook

The following simple program is used to create a blank Microsoft Excel Workbook.

ApachePoiDemo.java

package com.tutorialspoint;

import java.io.File;
import java.io.FileOutputStream;

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

public class ApachePoiDemo {
   public static void main(String[] args)throws Exception {
      //Create Blank workbook
      XSSFWorkbook workbook = new XSSFWorkbook(); 

      //Create file system using specific name
      FileOutputStream out = new FileOutputStream(new File("example.xlsx"));

      //write operation workbook using file out object 
      workbook.write(out);
      out.close();
      workbook.close();
      System.out.println("example.xlsx written successfully");
   }
}

Output

If your system environment is configured with the POI library, it will compile and execute to generate the blank Excel file named example1.xlsx in your current directory and display the following output in the command prompt.

example1.xlsx written successfully

Example - Open Existing Workbook

Use the following code to open an existing workbook.

ApachePoiDemo.java

package com.tutorialspoint;

import java.io.File;
import java.io.FileInputStream;

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

public class ApachePoiDemo {
   public static void main(String args[])throws Exception { 
	   try {
         File file = new File("example.xlsx");
         FileInputStream fIP = new FileInputStream(file);

         //Get the workbook instance for XLSX file 
         XSSFWorkbook workbook = new XSSFWorkbook(fIP);

         if(file.isFile() && file.exists()) {
            System.out.println("example.xlsx file open successfully.");
         } else {
            System.out.println("Error to open openworkbook.xlsx file.");
         }
         workbook.close();
      } catch(Exception e) {
         System.out.println("Error to open openworkbook.xlsx file." + e.getMessage());
      }
   }
}

Output

Run the above code and verify the output −

example.xlsx file open successfully.

After opening a workbook, you can perform read and write operations on it.

Advertisements