Quick introduction to Apache POI
Chapters
Opening and creating a Workbook using Apache POI
Wokring with Workbooks
Create new Workbooks and open existing Workbooks in java shown below:
Create Blank Workbook
Creating blank Microsoft Excel Workbook as shown below
The example below creates a 2003 format XLS and a new format supported from Excel 2007 i.e. XLSX
import java.io.*; import org.apache.poi.xssf.usermodel.*; public class workbookexcel { public static void main(String[] args) throws Exception { // create a old format XLS workbook Workbook wb = new HSSFWorkbook(); FileOutputStream fileOut = new FileOutputStream("c:\poi\workbook.xls"); wb.write(fileOut); fileOut.close(); // create a XLSX workbook Workbook wb = new XSSFWorkbook(); FileOutputStream fileOut = new FileOutputStream("c:\poi\workbook.xlsx"); wb.write(fileOut); fileOut.close(); } }
Save code as workbookexcel.java and compile and execute it from the command prompt as follows:
$javac workbookexcel.java
$java workbookexcel
If system environments are configured properly with POI library, it will compile ok and execute to generate the blank Excel file workbookexcel.xlsx
in C:\poi
directory.
How to open an existing workbook
Here is an example code that will open a worksheet we just created. In this example we will use our workbook.xlsx file that we created in our previous example
import java.io.*; import org.apache.poi.xssf.usermodel.*; public class workbookopen { public static void main(String args[]) throws Exception { File xlsx = new File("C:\poi\workbook.xlsx"); FileInputStream is = new FileInputStream(xlsx); XSSFWorkbook workbook = new XSSFWorkbook(is); if (xlsx.isFile() && xlsx.exists()) { System.out.println("hurray! We've just opened a workbook"); } else { System.out.println("Ahh! there was an error. Please make sure that the file path is correct."); } } }
Save code as workbookopen.java and then compile and execute it from command prompt as shown:
$javac workbookopen.java
$java workbookopen
It will compile and execute to generate the following output.
hurray! We've just opened a workbook
Now that you've opened a workbook, you are able to do all sort of different things with it. You can perform write and read operations. Add rows, cells, forumulas etc.
Description
This tutorial covers Apache POI, This tutorial is divided into 12 parts as listed below
- What is Apache POI
- Environment
- Core Classes
- Workbooks
- Spreadsheets
- Cells
- Fonts
- Formula
- Hyperlink and defiining Print Area
- Database
Let us know if we made any error, your feedback is important.
Prerequisites
Its is important that you have working knowledge of Java Programming language
Audience
Beginners seeking a quick introduction to Apache POI
Learning Objectives
To get you started with Apache POI
Author: Subject Coach
Added on: 10th Mar 2015
You must be logged in as Student to ask a Question.
None just yet!