springboot2集成Excel

阅读更多
1导入excel包
compile('org.apache.poi:poi-ooxml-schemas:3.17')
compile('org.apache.poi:poi-ooxml:3.17')
compile('org.apache.poi:poi:3.17')

第二步导入
@ApiOperation(value = "导出一个测试")
@GetMapping("/exportExcel")
public void exportExcel(HttpServletResponse response, HttpServletRequest request) throws Exception {
//接收参数
String ids = request.getParameter("ids");

//查询数据,实际可通过传过来的参数当条件去数据库查询,在此我就用空集合(数据)来替代
List result  = new ArrayList<>();
User user =new User();
user.setId("1");
user.setPassWord("111");
user.setUserName("我是张三111");

User user1 =new User();
user1.setId("2");
user1.setPassWord("222");
user1.setUserName("我是张三222");

User user2 =new User();
user2.setId("3");
user2.setPassWord("333");
user2.setUserName("我是张三333");
result.add(user);
result.add(user1);
result.add(user2);
//创建poi导出数据对象
SXSSFWorkbook sxssfWorkbook = new SXSSFWorkbook();

//创建sheet页
SXSSFSheet sheet = sxssfWorkbook.createSheet("开复工项目");

CellRangeAddress region1 = new CellRangeAddress(0, 1, (short) 0, (short) 12);
//参数1:起始行 参数2:终止行 参数3:起始列 参数4:终止列
sheet.addMergedRegion(region1);
SXSSFRow headTitle = sheet.createRow(0);
headTitle.createCell(0).setCellValue("重点工程项目计划表");

//创建表头
SXSSFRow headRow = sheet.createRow(4);
//设置表头信息
headRow.createCell(0).setCellValue("序号");
headRow.createCell(1).setCellValue("项目分类");
headRow.createCell(2).setCellValue("投资分类");

// 遍历上面数据库查到的数据
for (User pm : result) {
SXSSFRow dataRow = sheet.createRow(sheet.getLastRowNum() + 1);
dataRow.createCell(0).setCellValue(pm.getId());
dataRow.createCell(1).setCellValue(pm.getPassWord());
dataRow.createCell(2).setCellValue(pm.getUserName());

}
// 下载导出
String filename = "平台工程信息表";
// 设置头信息
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,springboot)