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.

Create Blank Workbook

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

import java.io.*;
import org.apache.poi.xssf.usermodel.*;

public class CreateWorkBook {
   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("createworkbook.xlsx"));

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

Let us save the above Java code as CreateWorkBook.java, and then compile and execute it from the command prompt as follows −

$javac CreateWorkBook.java
$java CreateWorkBook

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

createworkbook.xlsx written successfully

Open Existing Workbook

Use the following code to open an existing workbook.

import java.io.*;
import org.apache.poi.xssf.usermodel.*;

public class OpenWorkBook {
   public static void main(String args[])throws Exception { 
	   try {
         File file = new File("openworkbook.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("openworkbook.xlsx file open successfully.");
         } else {
            System.out.println("Error to open openworkbook.xlsx file.");
         }
      } catch(Exception e) {
         System.out.println("Error to open openworkbook.xlsx file." + e.getMessage());
      }
   }
}

Save the above Java code as OpenWorkBook.java, and then compile and execute it from the command prompt as follows −

$javac OpenWorkBook.java
$java OpenWorkBook

It will compile and execute to generate the following output.

openworkbook.xlsx file open successfully.

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

Advertisements