excel之导出

1.Maven依赖的jar包

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
     <version>3.14</version>
</dependency>
在引入这个东西之后,项目中会自动引入三个poi相关的jar,如下图:
 

2.controller代码

public Object exportExcel(HttpServletResponse response, StudentStatisticListForm studentStatisticListForm)
throws IOException {
studentStatisticService.exportExcel(response, studentStatisticListForm);
return "导出成功";
}

3.业务层代码

 

public void exportExcel(HttpServletResponse response, StudentStatisticListForm studentStatisticListForm)
throws IOException {
//创建HSSFWorkbook对象(excel的文档对象)
HSSFWorkbook wb = new HSSFWorkbook();
//建立新的sheet对象(excel的表单)
HSSFSheet sheet = wb.createSheet("成绩表");
//在sheet里创建第一行,参数为行索引(excel的行),可以是0~65535之间的任何一个
HSSFRow row1 = sheet.createRow(0);
//创建单元格(excel的单元格,参数为列索引,可以是0~255之间的任何一个
HSSFCell cell = row1.createCell(0);
//设置单元格内容
cell.setCellValue("学员考试成绩一览表");
//合并单元格CellRangeAddress构造参数依次表示起始行,截至行,起始列, 截至列 无论是行还是列都是从0开始计数
sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 8));
//在sheet里创建第二行
HSSFRow row2 = sheet.createRow(1);
//创建单元格并设置单元格内容
row2.createCell(0).setCellValue("学生姓名");
row2.createCell(1).setCellValue("作品");
row2.createCell(2).setCellValue("回帖");
row2.createCell(3).setCellValue("平均星级");
row2.createCell(4).setCellValue("总字数");
row2.createCell(5).setCellValue("获得鲜花");
row2.createCell(6).setCellValue("获得评论");
row2.createCell(7).setCellValue("评论他人");
row2.createCell(8).setCellValue("送鲜花数");
//在sheet里创建第三行
List<Map<String, Object>> list = list(studentStatisticListForm);//这里是开发人员要提供的接口

//把查询的数据循环添加到每行的每个单元格中
for (int i = 0; i < list.size(); i++) {
HSSFRow rowNew = sheet.createRow(2 + i);
rowNew.createCell(0).setCellValue(list.get(i).get("name").toString());
rowNew.createCell(1).setCellValue(list.get(i).get("opusCount").toString());
rowNew.createCell(2).setCellValue(list.get(i).get("repliesCount").toString());
rowNew.createCell(3).setCellValue(list.get(i).get("starCount").toString());
rowNew.createCell(4).setCellValue(list.get(i).get("wordNumber").toString());
rowNew.createCell(5).setCellValue(list.get(i).get("getFlower").toString());
rowNew.createCell(6).setCellValue(list.get(i).get("getComment").toString());
rowNew.createCell(7).setCellValue(list.get(i).get("commentOthPerson").toString());
rowNew.createCell(8).setCellValue(list.get(i).get("sendFlower").toString());
}

//输出Excel文件
OutputStream output = response.getOutputStream();
response.reset();
response.setHeader("Content-disposition", "attachment; filename=学生统计.xls");
response.setContentType("application/msexcel");
wb.write(output);
output.close();
}

 结束,此时你应该能够正常导出数据了

原文地址:https://www.cnblogs.com/htyj/p/7286269.html