一、目的
为了便于文件打印或查看数据,需要将数据导出
二、代码
package com.sinldo.test; import com.sinldo.po.Student; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import java.io.FileOutputStream; import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; import java.util.UUID; public class POI { public static void main(String[] args) throws ParseException { /** * 1.创建一个Excel文件 */ HSSFWorkbook wb=new HSSFWorkbook(); /** * 2.生成Excel文件名字 */ HSSFSheet sheet=wb.createSheet("工作表"); /** * 3.添加第0行,即添加表头 */ HSSFRow row=sheet.createRow(0); /** * 4.设置表头的内容 */ //创建一个单元格 HSSFCell cell = row.createCell(0); //设置单元格的内容 cell.setCellValue("学号"); cell = row.createCell(1); cell.setCellValue("姓名"); cell = row.createCell(2); cell.setCellValue("年龄"); cell = row.createCell(3); cell.setCellValue("生日"); //创建数据 SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd"); Student s1=new Student(1,"小雅",12,sdf.parse("1997-03-12")); Student s2=new Student(1,"小雅",12,sdf.parse("1997-03-12")); Student s3=new Student(1,"小雅",12,sdf.parse("1997-03-12")); Student s4=new Student(1,"小雅",12,sdf.parse("1997-03-12")); Student s5=new Student(1,"小雅",12,sdf.parse("1997-03-12")); //将数据添加到list中 List<Student> list=new ArrayList<>(); list.add(s1); list.add(s2); list.add(s3); list.add(s4); list.add(s5); /** * 5.将数据添加到表格中 */ for (int i = 0; i <5; i++) { row = sheet.createRow(i+1); Student stu = list.get(i); //设置单元格的数据 row.createCell(0).setCellValue(stu.getId()); row.createCell(1).setCellValue(stu.getName()); row.createCell(2).setCellValue(stu.getAge()); cell = row.createCell((short) 3); cell.setCellValue(new SimpleDateFormat("yyyy-MM-dd").format(stu.getBirth())); } /** * 6.声明下载到的地址和文件名称 */ try { //为了不覆盖,能多次下载,文件名后缀加上一个UUID。 String uuid = UUID.randomUUID().toString().replaceAll("-",""); //文件输出流 FileOutputStream fos=new FileOutputStream("E:/student"+uuid+".xls"); wb.write(fos); //关闭输出流 fos.close(); } catch (IOException e) { e.printStackTrace(); } } }