Apache POI to create excel file
Maven dependencies:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.9</version>
</dependency>
Example:
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class WorkingWithExcel {
public static void main(String[] args) {
createWorkBook();
}
/**
* Create workbook with one work sheet. Once work sheet is created, then
* content will be added to the work sheet.
*/
private static void createWorkBook() {
final String WORKBOOK_NAME = "emp_workbook.xlsx";
if (!Files.exists(Paths.get(WORKBOOK_NAME))) {
try (FileOutputStream fos = new FileOutputStream(new File("emp_workbook.xlsx"))) {
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("emp_details");
int rowcount = 0;
Row row = sheet.createRow(rowcount++);
Object[] colHeading = getColumnHeadings();
int i = 0;
for (Object obj : colHeading) {
Cell cell = row.createCell(i++);
cell.setCellValue((String) obj);
}
Object empData[][] = getEmpData();
for (Object obj[] : empData) {
i = 0;
row = sheet.createRow(rowcount++);
for (Object ob : obj) {
Cell cell = row.createCell(i++);
cell.setCellValue((String) ob);
}
}
workbook.write(fos);
System.out.println("Work book is created successfully with name :" + WORKBOOK_NAME);
} catch (IOException e) {
e.printStackTrace();
}
} else {
System.out.println("File already exists with the name :" + WORKBOOK_NAME);
}
}
/**
* To return work sheet headings
*
* @return
*/
private static Object[] getColumnHeadings() {
return new Object[] { "EMPNO", "ENAME", "EMAIL", "CITY" };
}
/**
* Actual data to add to work sheet
*
* @return
*/
public static Object[][] getEmpData() {
return new Object[][] { { "SPAN001", "Lakshman", "lakshman.a@spaneos.com", "Bangalore" },
{ "SPAN002", "Krish", "krish.t@spaneos.com", "Bangalore" },
{ "SPAN003", "Suresh", "suresh.s@spaneos.com", "Bangalore" },
{ "SPAN004", "Ramesh", "ramesh.r@spaneos.com", "Bangalore" } };
}
}
No comments:
Post a Comment