超级简单好用的poi组件导出Excel功能:
一、pom.xml导入poi的jar包
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.14</version>
</dependency>
二、jsp代码
<a href="/export/exportXls" type="button" class="btn btn-sm btn-default" ><i class="fa fa-upload"></i> 导出</a>
三、Controller层
@RequestMapping("/exportXls")
public void exportXls(HttpServletResponse response) throws Exception {
Workbook wb = datasService.exportXls();
// 文件下载的响应头(让浏览器访问资源的的时候以下载的方式打开,filename文件名)
response.setHeader("Content-Disposition","attachment;filename=export.xls");
// 创建 excel 文件
// 把 excel 的数据输出给浏览器
wb.write(response.getOutputStream());
}
四、Service层接口
public interface DatasService {
Workbook exportXls();
}
五、Service层实现类
public Workbook exportXls() {
// 创建 excel 文件
Workbook wb = new HSSFWorkbook();
// 创建 sheet
Sheet sheet = wb.createSheet("学生名单");
// 标题行
Row row = sheet.createRow(0);
// 设置内容到单元格中
row.createCell(0).setCellValue("学号");
row.createCell(1).setCellValue("姓名");
row.createCell(2).setCellValue("性别");
// 查询员工数据
List<Students> students = employeeMapper.selectAll();
for (int i = 0; i < students.size(); i++) {
Students student = students.get(i);
// 创建行(每个员工就是一行)
row = sheet.createRow(i + 1);
// 设置内容到单元格中
row.createCell(0).setCellValue(students.getStudentsId());
row.createCell(1).setCellValue(students.getName());
row.createCell(2).setCellValue(students.getSex());
}
return wb;
}
图示: