Excel填充数据并下载
每篇一句励志:在你往上爬的时候,一定要保持梯子的整洁,否则你下来时可能会滑倒。
话不多说,直接上代码。
public void exportMsgList(String companyCode, String companyName, String planTime, Integer type, HttpServletResponse response) {
try {
//这是使用SQLSERVER数据库;拼接sql
StringBuffer sb = new StringBuffer();
sb.append("select * from T_COMPANY_MSG where 1=1 ");
if(StringUtils.isNotBlank(companyCode)){
sb.append(" and COMPANY_CODE = '"+companyCode+"'");
}
if(type != null){
sb.append(" and PERIOD_TYPE = "+type);
}
if(StringUtils.isNotBlank(planTime)){
sb.append(" and MONTH = '"+planTime+"'");
}
sb.append(" order by CREATE_TIME");
Query nativeQuery = entityManager.createNativeQuery(sb.toString(), TCompanyMsg.class);
List<TCompanyMsg> resultList = nativeQuery.getResultList();
//拿到excel,我的是放在resources下的static里
InputStream stream = FileUtil.class.getClassLoader().getResourceAsStream("static/" + "企业周期上报计划校验记录.xlsx");
XSSFWorkbook wb = new XSSFWorkbook(stream);
response.reset();
//设置下载文档格式
response.setContentType("application/msexcel;charset=UTF-8");
if(CollectionUtils.isNotEmpty(resultList)){
//填充数据
//拿到excel的sheet
XSSFSheet sheet = wb.getSheet("sheet1");
int xuHao = 0;
//从哪行开始填充数据
int rowNum = 6;
//循环数据集
for (TCompanyMsg tCompanyMsg : resultList) {
xuHao++;
//复制行。一般有模板行需要复制
//方法的参数为:sheet.copyRows(模板行的开始,模板行的结束,填充数据的开始行,用new的就可以,如果有其他需求方法里可放参数);
sheet.copyRows(5,5,rowNum,new CellCopyPolicy());
//此处如果你的excel里没有已经处理过的行就需要创建行
XSSFRow row = sheet.getRow(rowNum);
// XSSFRow row = sheet.createRow(rowNum);//创建行。如果你是创建行可能单元格也需要创建
row.getCell(0).setCellValue(xuHao);
row.getCell(1).setCellValue(tCompanyMsg.getCompanyCode());
row.getCell(2).setCellValue(tCompanyMsg.getCompanyName());
row.getCell(3).setCellValue(tCompanyMsg.getMonth());
row.getCell(4).setCellValue(tCompanyMsg.getSheetName());
if(tCompanyMsg.getCreateTime() != null){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
row.getCell(5).setCellValue(sdf.format(tCompanyMsg.getCreateTime()));
}
rowNum++;//行++
}
//删除第一行的模板行。
sheet.shiftRows(rowNum,sheet.getLastRowNum(),-1);
}
//拼装导出的名称
String excelName = companyName + "企业周期上报计划校验记录";
response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode(excelName, "UTF-8") + ".xlsx");
BufferedOutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
//通过流返回前端
wb.write(outputStream);
outputStream.flush();
} catch (Exception e) {
log.error("导出Excle报错,{}",e);
}
}