代码实现:
package com.woniu.controller;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniu.bean.Subject;
import com.woniu.service.ISubjectService;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
/**
* @author vampire
* @date 2022-06-09
* @desc
*/
@CrossOrigin
@RestController
@RequestMapping("/POI")
public class POIController {
@Autowired
ISubjectService subjectService;
@GetMapping("excel")
public void sendExcel(Integer currentPage, Integer pageSize, String userName, HttpServletResponse response) throws IOException {
Workbook wb = new HSSFWorkbook();
// 准备分页数据
Page<Subject> ap = new Page<>(currentPage, pageSize);
Page<Subject> subjectPage = subjectService.page(ap);
List<Subject> subjects = subjectPage.getRecords();
// 创建学科表
Sheet sheet = wb.createSheet("学科");
// 定义第一行数据
Row row = sheet.createRow(0);
row.createCell(0).setCellValue("id");
row.createCell(1).setCellValue("学科名称");
row.createCell(2).setCellValue("年级");
Integer i=1;
for (Subject subject : subjects) {
Row r = sheet.createRow(i);
r.createCell(0).setCellValue(subject.getId());
r.createCell(1).setCellValue(subject.getName());
r.createCell(2).setCellValue(subject.getLevelName());
i++;
}
response.setHeader("content-disposition","attachment;filename=user.xls");
ServletOutputStream os = response.getOutputStream();
wb.write(os);
}
}
解析: