Springboot项目百万条数据导出到excel表格实战
1实现百万条数据导入到excel表格里
第一步导入依赖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;
}
第三步后台代码
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.party.common.journalSheet.PartyAllMettingFrequencyMonthlyEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@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();
}
}
下载成功后打开excel表格 姓名年龄里应该是数据库查询出的数据,在此我是手写的假数据给大家观看一下成果
下一篇:
Hystrix服务容错降级使用
