IN my previous post, I posted code for reading excel file using Apache POI library. In this post I'll cover, how can we write data into excel. Here is the code:
package com.qa.test; import java.io.FileOutputStream; import java.util.Iterator; import java.util.List; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; public class SpreadSheetWriter { /** This method writes data to new excel file **/ public static void writeDataToExcelFile(List> data, String fileName) { try{ HSSFWorkbook myWorkBook = new HSSFWorkbook(); HSSFSheet mySheet = myWorkBook.createSheet(); HSSFRow myRow = null; HSSFCell myCell = null; //Create header row createHeaderRow(mySheet); int rowNum = 1; Iterator
> iter = data.iterator(); while(iter.hasNext()) { myRow = mySheet.createRow(rowNum++); int cellNum = 0; List
key = iter.next(); for(String values: key) { myCell = myRow.createCell(cellNum++); myCell.setCellValue(values); } } FileOutputStream out = new FileOutputStream(fileName); myWorkBook.write(out); out.close(); }catch(Exception e){ e.printStackTrace(); } } }