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");
//创建第一行,起始为0
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("地址");
//序号,默认为1
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");
//设置ContentType请求信息格式
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);
}
正文完