Writing into a Excel File Using apache poi

Writing an excel file
Writing a file using POI is very simple and involve following steps:
  1. Create a workbook
  2. Create a sheet in workbook
  3. Create a row in sheet
  4. Add cells in sheet

Maven Dependencies:

<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.17</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -- >
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>3.17</version>
</dependency>
SAMPLE PROGRAM: 

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;

public class WriteIntoExcel {
public static FileOutputStream outFile;
public static HSSFWorkbook wb;
public static HSSFSheet sh;
static FileInputStream fis;

public static String filename;

public static void writeIntoExcel() throws IOException {
Date dt = new Date();
SimpleDateFormat ft = new SimpleDateFormat("E yyyy.MM.dd_hh:mm:ss_a_zzz");
filename = ft.format(dt);
outFile = new FileOutputStream(new File("./EXCELNAME" + filename + ".xls"));
wb.write(outFile);
}

@SuppressWarnings("unchecked")
public static void main(String[] args) throws IOException {

wb = new HSSFWorkbook();
try {
sh = wb.createSheet("SHEETNAME");
} catch (Exception e) {
sh = wb.getSheet("SHEETNAME");
}

try {
Row row1 = sh.createRow((short) 0);
row1.createCell(0).setCellValue("Output");
sh.createRow(1).createCell(0).setCellValue("ROW 1 CELL 0");
sh.getRow(2).createCell(1).setCellValue("ROW 2 CELL 1");
sh.getRow(3).createCell(2).setCellValue("ROW 3 CELL 2");

writeIntoExcel();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Excel Sheet will be created in this format:

EXCELNAME_Wed 2018.01.24_06:15:14_PM_IST.xls

NOTE:
You can implement you own code inside 2nd try and catch block as per your requirement.

Comments

Popular posts from this blog

Open Chrome browser in Headless Mode