Create Simple Excel(.xls) document using Apache POI
In this section, you will learn how to create a Simple Excel sheet having .xls extension using Apache POI library.
In the given below example, we will going to create a simple excel document having one sheet named as "FIRST SHEET" which have values on the first row and first column. The row contains text "FIRST SHEET".
In the below example, i have used Apache POI version 3.7. For downloading the above library click here.
The Code is given below :
import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFRichTextString; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; public class CreateSimpleExcelDemo { public static void main(String[] args) { // // Creating an instance of HSSFWorkbook. // HSSFWorkbook workbook = new HSSFWorkbook(); // // Create two sheets in the excel document and name it First Sheet and // Second Sheet. // HSSFSheet firstSheet = workbook.createSheet("FIRST SHEET"); HSSFSheet secondSheet = workbook.createSheet("SECOND SHEET"); HSSFRow rowA = firstSheet.createRow(0); HSSFCell cellA = rowA.createCell(0); cellA.setCellValue(new HSSFRichTextString("FIRST SHEET")); HSSFRow rowB = secondSheet.createRow(0); HSSFCell cellB = rowB.createCell(0); cellB.setCellValue(new HSSFRichTextString("SECOND SHEET")); // // To write out the workbook into a file we need to create an output // stream where the workbook content will be written to. // FileOutputStream fos = null; try { fos = new FileOutputStream(new File("xls/CreateExcelDemo.xls")); workbook.write(fos); } catch (IOException e) { e.printStackTrace(); } finally { if (fos != null) { try { fos.flush(); fos.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
Output :
The Content of the first sheet of "CreateExcelDemo.xls" is given below :
A | |
1 | FIRST SHEET |