ssm导出数据为excel
时间: 2023-07-25 16:39:44 浏览: 43
导出Excel是一个常见的功能需求,以下是一种基于SSM框架的导出Excel的实现方式:
1. 首先需要引入POI相关的依赖,可以在pom.xml中添加以下依赖:
```
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.1</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.1</version>
</dependency>
```
2. 在controller中添加导出Excel的方法,如下所示:
```
@RequestMapping("/exportExcel")
public void exportExcel(HttpServletResponse response) throws IOException {
// 获取要导出的数据
List<Student> studentList = studentService.getAllStudents();
// 创建工作簿
XSSFWorkbook workbook = new XSSFWorkbook();
// 创建工作表
XSSFSheet sheet = workbook.createSheet("学生信息表");
// 创建表头
XSSFRow row = sheet.createRow(0);
row.createCell(0).setCellValue("ID");
row.createCell(1).setCellValue("学号");
row.createCell(2).setCellValue("姓名");
row.createCell(3).setCellValue("性别");
row.createCell(4).setCellValue("出生日期");
row.createCell(5).setCellValue("地址");
row.createCell(6).setCellValue("电话");
row.createCell(7).setCellValue("照片");
row.createCell(8).setCellValue("备注");
row.createCell(9).setCellValue("所属宿舍");
// 填充数据
for (int i = 0; i < studentList.size(); i++) {
row = sheet.createRow(i + 1);
row.createCell(0).setCellValue(studentList.get(i).getId());
row.createCell(1).setCellValue(studentList.get(i).getStuNo());
row.createCell(2).setCellValue(studentList.get(i).getStuName());
row.createCell(3).setCellValue(studentList.get(i).getStuSex());
row.createCell(4).setCellValue(studentList.get(i).getStuBirth());
row.createCell(5).setCellValue(studentList.get(i).getStuAddress());
row.createCell(6).setCellValue(studentList.get(i).getStuPhone());
row.createCell(7).setCellValue(studentList.get(i).getStuPhoto());
row.createCell(8).setCellValue(studentList.get(i).getStuRemark());
row.createCell(9).setCellValue(studentList.get(i).getStuDormitory());
}
// 设置响应头信息
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment;filename=student.xls");
// 输出Excel文件
workbook.write(response.getOutputStream());
workbook.close();
}
```
3. 在前端页面中添加导出Excel的按钮,并绑定到controller中的导出方法上。
```
<a href="/exportExcel" class="btn btn-primary">导出Excel</a>
```
以上就是基于SSM框架导出Excel的一种实现方式,通过POI库构造Excel文件,并通过HttpServletResponse对象输出Excel文件。