1 package poi; 2 3 import java.io.File; 4 import java.io.FileOutputStream; 5 import java.io.IOException; 6 import java.text.SimpleDateFormat; 7 import java.util.Date; 8 9 import org.apache.commons.io.FileUtils; 10 import org.apache.poi.hssf.usermodel.HSSFCell; 11 import org.apache.poi.hssf.usermodel.HSSFRow; 12 import org.apache.poi.hssf.usermodel.HSSFSheet; 13 import org.apache.poi.hssf.usermodel.HSSFWorkbook; 14 15 public class PoiExpExcel { 16 17 public static void main(String[] args) { 18 //表頭 19 String[] title = {"name", "age", "sex", "date"}; 20 //建立工做薄 21 HSSFWorkbook workbook = new HSSFWorkbook(); 22 //建立sheet 23 HSSFSheet sheet = workbook.createSheet(); 24 //建立行 25 HSSFRow row = sheet.createRow(0); 26 27 HSSFCell cell = null; 28 for (int i = 0; i < title.length; i++) { 29 //建立單元格 30 cell = row.createCell(i); 31 //設置單元格內容 32 cell.setCellValue(title[i]); 33 } 34 //填寫數據 35 for (int i = 1; i < 10; i++) { 36 //建立行 37 HSSFRow nextrow = sheet.createRow(i); 38 HSSFCell cell2 = nextrow.createCell(0); 39 cell2.setCellValue("user"+1); 40 cell2 = nextrow.createCell(1); 41 cell2.setCellValue(12+i); 42 cell2 = nextrow.createCell(2); 43 cell2.setCellValue("M"); 44 cell2 = nextrow.createCell(3); 45 cell2.setCellValue( new SimpleDateFormat("yyyy-MM-dd").format(new Date())); 46 47 48 } 49 //建立文件 50 File file = new File("e:/poi_exp.xls"); 51 try { 52 file.createNewFile(); 53 //打開一個文件流 54 FileOutputStream stream = FileUtils.openOutputStream(file); 55 //將工做簿寫到文件流中 56 workbook.write(stream); 57 //關閉工做簿 58 workbook.close(); 59 //關閉流 60 stream.close(); 61 } catch (IOException e) { 62 e.printStackTrace(); 63 } 64 65 66 } 67 68 }