This example demonstrate how to create an excel document using Apache POI library. In this example we create a simple document containing two sheets which have a value on their first cell.
package org.kodejava.example.poi;
import org.apache.poi.hssf.usermodel.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class CreateExcelDemo {
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");
// Manipulate the firs sheet by creating an HSSFRow which represent a
// single row in excel sheet, the first row started from 0 index. After
// the row is created we create a HSSFCell in this first cell of the row
// and set the cell value with an instance of HSSFRichTextString
// containing the words FIRST 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.
try (FileOutputStream fos =
new FileOutputStream(new File("CreateExcelDemo.xls"))) {
workbook.write(fos);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Maven Dependencies
<!-- https://search.maven.org/remotecontent?filepath=org/apache/poi/poi/4.1.0/poi-4.1.0.jar -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.0</version>
</dependency>
Latest posts by Wayan (see all)
- How do I install Calibri font in Ubuntu? - January 24, 2021
- How do I create a generic class in Java? - January 1, 2021
- How do I convert java.util.TimeZone to java.time.ZoneId? - April 25, 2020
Very Cool! Thanks to Wayan Saryada!!!
Thanks Pak Wayan