Package Com.file.properties;import Java.io.file;import Java.io.filenotfoundexception;import Java.io.fileoutputstream;import Java.io.ioexception;import Java.util.arraylist;import java.util.Collections; Import java.util.date;import java.util.hashmap;import java.util.list;import java.util.map;import java.util.Set; Import Org.apache.poi.hssf.usermodel.hssfsheet;import Org.apache.poi.hssf.usermodel.hssfworkbook;import Org.apache.poi.ss.usermodel.cell;import Org.apache.poi.ss.usermodel.richtextstring;import Org.apache.poi.ss.usermodel.row;public class Createnewexcel {static void Createexcelfile (File createfile,string SheetName, map<string, object[]> data) {Hssfworkbook workbook = new Hssfworkbook (); Hssfsheet sheet = workbook.createsheet (sheetname); Set<string> Keyset=data.keyset (); List<string> keylist=new arraylist<string> (KeySet); Collections.sort (keylist); int rownum = 0;for (String key:keylist) {Row row = Sheet.createrow (rownum++); object[] Objarr = (object[]) data.get(key); int cellnum = 0;for (Object obj:objarr) {Cell cell = Row.createcell (cellnum++); if (obj instanceof Date) cell.setcel LValue ((richtextstring) obj), else if (obj instanceof Boolean) Cell.setcellvalue ((Boolean) obj), else if (obj instanceof String) Cell.setcellvalue ((string) obj), else if (obj instanceof Double) Cell.setcellvalue ((Double) obj);}} try {fileoutputstream out = new FileOutputStream (createFile), workbook.write (out); Out.close (); System.out.println ("Excel written successfully..");} catch (FileNotFoundException e) {e.printstacktrace ();} catch (IOException e) {e.printstacktrace ()}} /** * @param args */public static void main (string[] args) {file CreateFile = new File ("d:\\soapuistudy\\createexcelfile.x LS "); String sheetname = "Sample sheet"; map<string, object[]> data = new hashmap<string, object[]> ();d ata.put ("1", new object[] {"Emp No.", "Name", "S Alary "});d Ata.put (" 2 ", new object[] {1d," John ", 1500000d});d Ata.put (" 3 ", new object[] {2d," Sam ", 800000d});d Ata.put (" 4 ", New object[] {3d, "Dean", 700000d}); Createexcelfile (Createfile,sheetname,data);}}
Result:
[Java] Create Excel File Using Apache POI API