标签:
1.导出list集合类型数据文件
package com.mi.entity; import java.util.Date; public class Student { private int id; private String name; private int age; private Date birth; public Student(int id, String name, int age, Date birth) { super(); this.id = id; this.name = name; this.age = age; this.birth = birth; } }
生成excel文件代码
package com.mi.util; import java.io.File; import java.io.FileOutputStream; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFCellStyle; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import com.mi.entity.Student; public class CreateSimpleExcelToDisk { /** * 手工创建一个包含student的list * @return * @throws Exception */ private static List<Student> getStudent() throws Exception { List<Student> list = new ArrayList<>(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd"); Student user1 = new Student(1, "张三", 16, sdf.parse("1997-03-12")); Student user2 = new Student(2, "李四", 17, sdf.parse("1996-08-12")); Student user3 = new Student(3, "王五", 26, sdf.parse("1985-11-12")); list.add(user1); list.add(user2); list.add(user3); return list; } public static void main(String[] args) throws Exception { //第一步,创建一个webbook文件,对应一个excel文件 HSSFWorkbook wb = new HSSFWorkbook(); //第二部,在excel中添加一个sheet工作簿,参数为该工作簿名字,不写为默认; HSSFSheet sheet = wb.createSheet("学生表1"); //第三部,做sheet中添加表头第0行,注意老版本poi对excel的行数列数有限制short HSSFRow row = sheet.createRow((int)0); //第四部,创建单元格表头 设置表头居中 HSSFCellStyle style = wb.createCellStyle(); style.setAlignment(HSSFCellStyle.ALIGN_CENTER);//创建一个居中格式 //创建具体盛放数据的单元格,可以考虑把cell抽成共通对象去使用 HSSFCell cell = row.createCell((int) 0); cell.setCellValue("学号"); cell = row.createCell((int) 1); cell.setCellValue("姓名"); cell = row.createCell((int) 2); cell.setCellValue("年龄"); cell = row.createCell((int) 3); cell.setCellValue("生日"); //第五部,写入实体数据 实际应用中这些数据应该是从数据库中得到 List<Student> list = CreateSimpleExcelToDisk.getStudent(); for(int i=0;i<list.size();i++){ //每次新建一行然后在新行中插入list中的数据对象,有点繁琐,也许有更好的封装方法,留待后看 row = sheet.createRow((int)i+1); row.createCell((int)0).setCellValue(list.get(i).getId()); row.createCell((int)1).setCellValue(list.get(i).getName()); row.createCell((int)2).setCellValue(list.get(i).getAge()); row.createCell((int)3).setCellValue(new SimpleDateFormat("yyyy-mm-dd").format(list.get(i).getBirth())); } //第六部,将文件保存到指定位置 FileOutputStream fout = new FileOutputStream("D:/student.xls"); wb.write(fout); fout.close(); } }
效果:
注:.首先下载poi-3.6-20091214.jar,下载地址如下:
http://download.csdn.net/detail/evangel_z/3895051
标签:
原文地址:http://www.cnblogs.com/tingbogiu/p/5912691.html