简单的poi导出excel文件

/**
*
* 创建excel文件
*
*/
1
import java.io.FileOutputStream; 2 import java.io.IOException; 3 import java.util.Calendar; 4 import java.util.List; 5 6 import org.apache.poi.hssf.usermodel.HSSFCell; 7 import org.apache.poi.hssf.usermodel.HSSFRow; 8 import org.apache.poi.hssf.usermodel.HSSFSheet; 9 import org.apache.poi.hssf.usermodel.HSSFWorkbook; 10 11 public class PoiTest { 12 13 public static void main(String[] args) throws IOException { 14 15 16 17 //创建一个webbook,对应一个excel文件 18 HSSFWorkbook wb = new HSSFWorkbook(); 19 //在webbook中添加一个sheet。对应excel文件中的sheet 20 HSSFSheet sheet = wb.createSheet(); 21 //在sheet中添加表头第0行 22 HSSFRow row = sheet.createRow(0); 23 24 HSSFCell cell = row.createCell(0); 25 cell.setCellValue("aaaaaa"); 26 cell = row.createCell(1); 27 cell.setCellValue("bbbbbb"); 28 cell = row.createCell(2); 29 cell.setCellValue("cccccc"); 30 //接收utils.userResult方法的返回值 31 List recetion = new Utils().userResult(); 32 33 for (int i = 1; i < recetion.size()+1; i++) { 34 35 row = sheet.createRow(i); 36 37 } 38 39 System.out.println(row.getRowNum()); 40 41 for (int i = 0; i < recetion.size(); i++) { 42 row = sheet.getRow(i + 1); 43 System.out.println(row.getRowNum()); 44 User user = (User)recetion.get(i); 45 //创建单元格 46 row.createCell(0).setCellValue(user.getName()); 47 row.createCell(1).setCellValue(user.getAge()); 48 row.createCell(2).setCellValue(user.getOther()); 49 50 51 } 52 53 //保存文件 54 FileOutputStream fOut = new FileOutputStream("d:\\" + Calendar.getInstance().getTimeInMillis() + ".xls",false); 55 wb.write(fOut); 56 fOut.flush(); 57 fOut.close(); 58 } 59 }
/**
* javabean
*/
public
class User { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } public String getOther() { return other; } public void setOther(String other) { this.other = other; } private String age; private String other; }
/**
* 模拟数据库查询结果
*/
import
java.util.ArrayList; import java.util.List; public class Utils { @SuppressWarnings("rawtypes") public List userResult() { User user = new User(); user.setName("张1"); user.setAge("12"); user.setOther("aaaa"); User user1 = new User(); user1.setName("张2"); user1.setAge("12"); user1.setOther("a"); User user2 = new User(); user2.setName("张3"); user2.setAge("12"); user2.setOther("ccc"); User user3 = new User(); user3.setName("张4"); user3.setAge("12"); user3.setOther("bbb"); List<User> list = new ArrayList<User>(); list.add(user); list.add(user1); list.add(user2); list.add(user3); return list; } }

poi jar包下载地址:http://download.csdn.net/download/pumpkin09/7077011

posted @ 2016-08-29 11:28  孟大凡  阅读(294)  评论(0编辑  收藏  举报