Package Com.file.properties;import Java.io.file;import Java.io.fileinputstream;import java.io.FileOutputStream; Import Java.io.inputstream;import Java.util.hashtable;import Org.apache.poi.hssf.usermodel.hssfcellstyle;import Org.apache.poi.hssf.util.hssfcolor;import Org.apache.poi.ss.usermodel.cellstyle;import Org.apache.poi.xssf.usermodel.xssfcell;import Org.apache.poi.xssf.usermodel.xssfrow;import Org.apache.poi.xssf.usermodel.xssfsheet;import Org.apache.poi.xssf.usermodel.xssfworkbook;class WriteExcel {@ Suppresswarnings ("rawtypes") static void Savetoexcelfile (File writefile,hashtable table) {try {//write Data to Excel file Xssfworkbook WB; Xssfsheet sheet; Xssfrow Row; Xssfcell cell; int rowIndex = 0; if (writefile.exists ()) {InputStream excelfile = new FileInputStream (WriteFile); WB = new Xssfworkbook (excelfile); Sheet = wb.getsheetat (0);RowIndex = Sheet.getlastrownum (); RowIndex + = 1; row = Sheet.createrow (RowIndex); } else {wb = new Xssfworkbook (); Sheet = Wb.createsheet (); row = Sheet.createrow (0); Cell = Row.createcell (0); Cell.setcellvalue ("URL"); Cell = Row.createcell (1); Cell.setcellvalue ("PageRank"); Cell = Row.createcell (2); Cell.setcellvalue ("Alexarank"); row = Sheet.createrow (1); } CellStyle cs = Wb.createcellstyle (); Cs.setfillforegroundcolor (HSSFColor.GREEN.index); Cs.setfillpattern (Hssfcellstyle.solid_foreground); Cell = Row.createcell (0); Cell.setcellvalue (Table.get ("URL"). toString ()); Cell = Row.createcell (1); if (Integer.parseint (Table.get ("PageRank"). ToString ()) >= 5) Cell.setcellstyle (CS); Cell.setcellvalue (Table.get ("PageRank"). toString ()); Cell = Row.createcell (2); Cell.setcellvalue (Table.get ("Alexarank"). toString ()); FileOutputStream out = new FileOutputStream (WriteFile); Wb.write (out); Out.flush (); Out.close (); } catch (Exception e) {//TODO auto-generated catch block E.printstacktrace (); }}/** * @param args */@SuppressWarnings ({"Rawtypes", "Unchecked"}) public static void main (string[] args) {//TODO Au to-generated method Stub File WriteFile = New file ("D:\\soapuistudy\\writeexcel.xlsx"); Hashtable table = new Hashtable (); Table.put ("URL", "http:\\cn.bing.com"); Table.put ("PageRank", "5"); Table.put ("Alexarank", "13658988546"); Savetoexcelfile (writefile,table);}}
These 4 JARs is needed to run above codes:
Run 2 times, the Excel would show like below:
[Java] Write Excel File Using Apache POI API