java files

Java write to excel file

This post shows you how to write content to excel file using java poi library.

Required Jar File

Download Here
poi-3.17.jar
poi-ooxml-3.17.jar
poi-ooxml-schemas-3.17.jar
xmlbeans-2.6.0.jar

commons-collections4-4.1.jar

package com.candidjava.excel;

import java.io.File;
import java.io.FileOutputStream;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ExcelWrite {
	public static void main(String[] args)throws Exception {
		File file=new File("F:/ExcelFile/excelWrite1.xlsx");
		FileOutputStream fo=new FileOutputStream(file);
		XSSFWorkbook workbook=new XSSFWorkbook();
		XSSFSheet sheet=workbook.createSheet();
		Object[][] data={
				{"Book","Author","Price"},
				{"Head First Java", "Kathy Serria", 79},
                {"Effective Java", "Joshua Bloch", 36},
                {"Clean Code", "Robert martin", 42},
                {"Thinking in Java", "Bruce Eckel", 35},
				};
		int rowcount=0;
		for(Object[] book:data)
		{
			Row row=sheet.createRow(rowcount++);
			int columncount=0;
			for(Object book1:book)
			{
			Cell cell=row.createCell(columncount++);
			 if (book1 instanceof String) {
                 cell.setCellValue((String) book1);
             } else if (book1 instanceof Integer) {
                 cell.setCellValue((Integer) book1);
             }
			}
		}
		workbook.write(fo);
		workbook.close();
		System.out.println("File write completed successfully");
	}

}
File write completed successfully