怕自己忘记所以写了这边博客记录一下
编辑器用idea
SSM+ maven框架
excel表格用的包在pom.xml添加
!--导excel表-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
</dependency>
上代码
@RequestMapping("excelInfo")
public void info(HttpServletRequest request, HttpServletResponse response) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("1", "学生id");
map.put("2", "学生姓名");
map.put("3", "试卷编号");
map.put("4", "成绩");
HSSFWorkbook wb = new HSSFWorkbook();
Sheet sheet = wb.createSheet("成绩表");/*对应表格的sheet*/
List<Score> scores= scoreService.findAllScore();//这是从数据库获取的
List<String> allScore=new ArrayList<>();
for (Score score:scores) {
allScore.add(score.getStudentId());
allScore.add(score.getStudent_name());
allScore.add(score.getExam_name());
allScore.add(score.getScore()+"");
}
/*表头*/
Row row1 = sheet.createRow(0);
int a = 0;
for(String key : map.keySet()){
Cell cell = row1.createCell(a);
cell.setCellValue((String) map.get(key));
a++;
}
/*数据*/
int k=0;
for (int j = 1; j <=scores.size(); j++) {/*scores.size() 成绩单的数据条数*/
Row row = sheet.createRow(j);/*总的行数*/
for (int i =0;i<4;i++) {/*4个字段循环*/
Cell cell = row.createCell(i);
/*单元格填充 通过下标获取allScore列表的元素 每条数据四个元素,第五的元素从本行的第一单元格开始,以此类推*/
cell.setCellValue(allScore.get(k));
k++;
}
}
OutputStream fos = null;
try {
fos = response.getOutputStream();
String userAgent = request.getHeader("USER-AGENT");
String fileName = "test";
response.setCharacterEncoding("UTF-8");
response.setContentType("application/vnd.ms-excel;charset=utf-8");// 设置contentType为excel格式
response.setHeader("Content-Disposition", "Attachment;Filename=" + fileName + ".xls");
wb.write(fos);
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
前端代码
<th>
<button onclick="excelInfo()" type="button" class="layui-btn layui-btn-normal">导出成绩单</button>
</th>
<script>
function excelInfo() {
window.location.href ="/excelInfo";
}
</script>
本文参考这篇博客
https://blog.csdn.net/LUNG108/article/details/78970489