无模板实现导出操作

public void getexport(Ambassador ambassador,HttpServletResponse response) {
     //查询语句
List<Ambassador> ambassadorList = rwAmbassadorApplyMapper.selectExport(ambassador);
     //创建一个新的list集合存放过滤之后的数据
List<AmbassadorVo> detailVos = new ArrayList<>(); for(Ambassador info : ambassadorList) {
       //创建一个新的实体类,该实体类放入导出需要的字段名称 AmbassadorVo vo
= new ambassadorVo(); vo.setName(info.getName()); vo.setPhone(info.getPhone()); vo.setProductId(info.getProductId()); vo.setTime(info.getTime()); detailVos.add(vo); }
     //获取当前日期 String currDate
= DateUtil.getCurrentDateStr("yyyy-MM-dd"); StringBuffer buff = new StringBuffer("导出xxx");  //下载 String fileName = buff.append("_").append(currDate).append(".xlsx").toString();
     //导出文件存放的目录路径 String path
= SysConfig.getConfig("path");
List
<List<String>> head = getHead(); EasyExcel.write(path + File.separator + fileName).head(head).registerWriteHandler(new CustomCellWriteHandler()) .sheet("导出xxx").doWrite(detailVos); try { export(response, fileName); log.info("文件导出成功"); } catch (Exception e) { e.printStackTrace(); log.error("文件导出失败"); } } public List<List<String>> getHead() { List<List<String>> head = new ArrayList<>(); List<String> col1 = new ArrayList<>(); List<String> col2 = new ArrayList<>(); List<String> col3 = new ArrayList<>(); List<String> col4 = new ArrayList<>(); col1.add("用户名"); col2.add("手机号"); col3.add("产品"); col4.add("时间"); head.add(col1); head.add(col2); head.add(col3); head.add(col4); return head; }
protected void export(HttpServletResponse response, String fileName) throws Exception {
        response.setCharacterEncoding("UTF-8");
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        if (fileName.endsWith(".xlsx")) {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        } else {
            response.setContentType("application/octet-stream");
        }

        File file = new File(SysConfig.getConfig("path"), fileName);
        try (FileInputStream fileInputStream = new FileInputStream(file);
                InputStream is = new MultipartInputStream(fileInputStream);) {
            FileCopyUtils.copy(is, response.getOutputStream());
        } finally {
            if (file.exists()) {
                FileUtils.deleteQuietly(file);
            }
        }
    }
/**
*导出需要的实体类
**/
@Data
public class AmbassadorVo { /** 用户名 **/
  /** 根据导出需要的顺序填写index值,防止导出的数据位置不正确 **/  
@ExcelProperty(value = "用户名", index = 0) private String name; /** 手机号 **/ @ExcelProperty(value = "手机号", index = 1) private String phone; /** 产品 **/ @ExcelProperty(value = "产品", index = 2) private String productId; /** 时间 **/ @ExcelProperty(value = "时间", index = 3) private String time; }
原文地址:https://www.cnblogs.com/wnwn/p/14452295.html