将查询列表内容保存到excel表格中,并保存到相应的盘中

1、先导入相应的jar包

2、一个小的Demo测试【实体类+测试类:保存excel的方法】

Student实体类

public class Student{

  private int id;

  private String name;

  private String email;

  private Date birth;

  //相应的set、get方法

  还有构造器(有参、无参的)

  ···············

}

Test测试类

public class Test{

  public static List<Student> getStudent() throws ParseException{

    List list = new ArrayList();

    SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");//转换时间格式

    Student stu = new Student(1,"haha","123@13",sf.parse("1992-09-20"));

    ·······

    list.add(stu);

    return list;

  }

  //具体的实现导出excel表格的程序

  public static void main(String[] args){

    //第一步,创建workbook,对应一个excel文件

    HSSFWorkbook wb = new HSSFWorkbook();

    //第二步,在workbook中创建一个sheet

    HSSFSheet sheet = wb.createSheet();

    //第三步,在sheet中创建表头

    HSSFRow row = sheet.createRow(0);//或者((int)0);

    //第四步,创建单元格样式、单元格

    HSSFCellStyle style = wb.createCellStyle();

    style.setAlignment(HSSFCellStyle.ALIGN_GENERAL);//单元格样式

    HSSFCell cell = row.createCell(0);

    cell.setCellValue("学号");
    cell.setCellStyle(style);
    cell = row.createCell(1);
    cell.setCellValue("姓名");
    cell.setCellStyle(style);
    cell = row.createCell(2);

    ·····表的第一行【行头】

    //第五步,写入实体数据

    List list = Test.getStudent();

    for(){ 

      row = sheet.createRow(i+1);
      Student stu = (Student) list.get(i);
      //设置单元格的值
      row.createCell(0).setCellValue(stu.getId());
      row.createCell(1).setCellValue(stu.getName());

      cell = row.createCell(3);//对时间格式进一步转换
      cell.setCellValue(new SimpleDateFormat("yyyy-MM-dd").format(stu.getBirth()));

    }

    //第六步 ,将创建好的文件输出
    try {
      FileOutputStream fout = new FileOutputStream("d:/student.xls");
      wb.write(fout);
      fout.close();
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

   }

}

程序完成,运行,会在d盘的目录下看到stu.xls这样子的一个表格;

 

posted @ 2015-08-27 11:51  FanSunny  阅读(518)  评论(0编辑  收藏  举报