//第一步导入依赖jar包
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>3.17</version>
</dependency>
=================================================================
//可以给页面上设置一个按钮,给按钮一个点击事件来触发此方法
function exportExcel() {
//条件有条件可以在此设置一个条件
var accounttime = $.trim($("#accounttime").val());
//跳转到后台的方法
window.location.href="http://localhost:8080/partyMetting/exportExcel?accounttime="+ accounttime;
}
=================================================================
//后台代码
@RestController
@RequestMapping("/partyMetting")
public class test {
@RequestMapping("/exportExcel")
public void exportExcel(HttpServletResponse response, HttpServletRequest request) throws Exception{
//接收参数
String accounttime = request.getParameter("accounttime");
//查询数据,实际可通过传过来的参数当条件去数据库查询,在此我就用空集合(数据)来替代
List<> list = new ArrayList<>();
//创建poi导出数据对象
SXSSFWorkbook sxssfWorkbook = new SXSSFWorkbook();
//创建sheet页
SXSSFSheet sheet = sxssfWorkbook.createSheet("sheet页名字");
//创建表头
SXSSFRow headRow = sheet.createRow(0);
//设置表头信息
headRow.createCell(0).setCellValue("序号");
headRow.createCell(1).setCellValue("姓名");
headRow.createCell(2).setCellValue("年龄");
// 遍历上面数据库查到的数据
for (PartyAllMettingFrequencyMonthlyEntity pm : list) {
//序号
int x = 1;
//填充数据
SXSSFRow dataRow = sheet.createRow(sheet.getLastRowNum() + 1);
//序号
dataRow.createCell(0).setCellValue(x);
//看你实体类在进行填充
dataRow.createCell(1).setCellValue(pm.username);
dataRow.createCell(2).setCellValue(pm.age);
x++;
}
// 下载导出
String filename = "导出excel表格名字";
// 设置头信息
response.setCharacterEncoding("UTF-8");
response.setContentType("application/vnd.ms-excel");
//一定要设置成xlsx格式
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename + ".xlsx", "UTF-8"));
//创建一个输出流
ServletOutputStream outputStream = response.getOutputStream();
//写入数据
sxssfWorkbook.write(outputStream);
// 关闭
outputStream.close();
sxssfWorkbook.close();
}
}