pom依赖:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.14</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>3.14</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.14</version>
</dependency>
HTML5 代码:
<a th:class="${active == '/uploadExcel.html'?'nav-link active':'nav-link'}" th:href="@{/admin/exportData}">导出学生信息</a>
service实现类代码
@Override
public XSSFWorkbook exportData(HttpServletResponse response) {
List<Student> students = studentDao.findAll();
XSSFWorkbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet("Student");
Row titleRow = sheet.createRow(0);
titleRow.createCell(0).setCellValue("序号");
titleRow.createCell(1).setCellValue("学号");
titleRow.createCell(2).setCellValue("姓名");
titleRow.createCell(3).setCellValue("身份证");
titleRow.createCell(4).setCellValue("年龄");
titleRow.createCell(5).setCellValue("地址");
int cell = 1;
for (Student student : students) {
Row row = sheet.createRow(cell);
row.createCell(0).setCellValue(cell);
row.createCell(1).setCellValue(student.getId());
row.createCell(2).setCellValue(student.getName());
row.createCell(3).setCellValue(student.getIdCard());
row.createCell(4).setCellValue(student.getAge());
row.createCell(5).setCellValue(student.getAddress());
cell++;
}
String fileName = "学生信息表.xlsx";
OutputStream outputStream =null;
try {
fileName = URLEncoder.encode(fileName,"UTF-8");
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-disposition", "attachment;filename=" + fileName);
outputStream = response.getOutputStream();
wb.write(outputStream);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
outputStream.flush();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return wb;
}
controller层代码:
@GetMapping("/exportData")
public void exportData(HttpServletResponse response){
studentService.exportData(response);
}