poi实现导出excel

1.导入poi所需的jar包

解压后导入其中的jar包

 

 2.实现在浏览器中将查询到的数据导入一个excel文件并实现下载(以学生表为例)

@RequestMapping("/exportStudent.action")
public void exportStudent(HttpServletResponse response) throws IOException{
List<Student> entities = studentService.getObjects();

//下载处理
//设置头
response.setHeader("content-disposition", "attachment;filename="+System.currentTimeMillis()+".xlsx");
//获取下载读取的流对象
OutputStream outputStream = response.getOutputStream();

//创建一个workbook对象
Workbook wb=new XSSFWorkbook();

Sheet sheet = wb.createSheet("学生信息");

Row r0 = sheet.createRow(0);
Cell c0 = r0.createCell(0);
c0.setCellValue("序号");
Cell c1=r0.createCell(1);
c1.setCellValue("学生姓名");
Cell c2=r0.createCell(2);
c2.setCellValue("学生学号");
Cell c3=r0.createCell(3);
c3.setCellValue("卡号");
Cell c4=r0.createCell(4);
c4.setCellValue("联系电话");
Cell c5=r0.createCell(5);
c5.setCellValue("密码");

//行
for(int row=0;row<entities.size();row++){
Row rw = sheet.createRow(row+1);
Student student=entities.get(row);
//列
Cell cell0 = rw.createCell(0);
cell0.setCellValue(student.getId());
Cell cell1 = rw.createCell(1);
cell1.setCellValue(student.getStu_name());
Cell cell2 = rw.createCell(2);
cell2.setCellValue(student.getStu_no());
Cell cell3 = rw.createCell(3);
cell3.setCellValue(student.getCard_no());
Cell cell4 = rw.createCell(4);
cell4.setCellValue(student.getPhone());
Cell cell5=rw.createCell(5);
cell5.setCellValue(student.getPassword());

}
wb.write(outputStream);
outputStream.close();
}

 

3.导出表格如图

 

posted @ 2017-06-11 14:15  freezy风  阅读(125)  评论(0编辑  收藏  举报