import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.Date; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFCellStyle; import org.apache.poi.hssf.usermodel.HSSFDataFormat; import org.apache.poi.hssf.usermodel.HSSFRichTextString; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; // The following example code demonstrates how to create an Excel // file using the org.apache.poi library. In the sample file, // a String, Date, Boolean, and Number are added to individual cells // in the spreadsheet. public class CreateExcelFile { public static void main(String[] args) { HSSFWorkbook workbook = new HSSFWorkbook(); HSSFSheet firstSheet = workbook.createSheet("Sheet 1"); // Write a String in Cell 1A HSSFRow row1 = firstSheet.createRow(0); HSSFCell cell1A = row1.createCell(0); cell1A.setCellValue(new HSSFRichTextString("Sample String")); // Write a Date in Cell 2B HSSFRow row2 = firstSheet.createRow(1); HSSFCell cell2B = row2.createCell(1); cell2B.setCellValue(new Date()); // Format the Date so it looks like a date HSSFCellStyle cellStyle = workbook.createCellStyle(); cellStyle = workbook.createCellStyle(); cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy h:mm")); cell2B.setCellStyle(cellStyle); // Write a Boolean in Cell 3C HSSFRow row3 = firstSheet.createRow(2); HSSFCell cell3C = row3.createCell(2); cell3C.setCellValue(true); // Write a Number in Cell 4D HSSFRow row4 = firstSheet.createRow(3); HSSFCell cell4D = row4.createCell(3); cell4D.setCellValue(3.14); FileOutputStream fileOutputStream = null; try { fileOutputStream = new FileOutputStream(new File("/Temp/Test3.xls")); workbook.write(fileOutputStream); } catch (IOException e) { e.printStackTrace(); } finally { if (fileOutputStream != null) { try { fileOutputStream.flush(); fileOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } } }Here is a screenshot of the generated Excel File:
Piece of cake!!!