poi方式创建Excel文件

 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 }

 

posted @ 2015-04-27 18:02  韩不懂  阅读(305)  评论(0编辑  收藏  举报