easyexcel 复制表头,合并表头,自定义表头名称、表头数量

效果

接口返给前端下载路径

 

@SneakyThrows
@GetMapping("/exportDetailed/{voteId}")
public AjaxResult exportVote(@PathVariable Integer voteId)  {
    // 准备导出数据

    String s = generateExcel(voteId);


    return AjaxResult.success(s);
}

方法

public String   generateExcel(Integer voteId){

    // 判断要下载的数据是否存在
    AppVote appVote = appVoteService.selectAppVoteById(voteId);
    if (appVote==null){
        throw new ServiceException("投票不存在");
    }
    // 自定义的标题 ,如同意,中立,拒绝
    List<AppVoteOption> appVoteOptions = appVoteOptionMapper.selectByVoteId(voteId);
    // 内容数据
    List<AppVoteDetailedVO> appVoteDetailedVO =  appVoteRecordMapper.selectVoteid(voteId);
    //标头
    String title = appVote.getTitle();
    // 选项标题
    String content = appVote.getContent();
    //表格头
    ArrayList<List<String>> head = new ArrayList<>();
    List<String> head1 = new ArrayList<>();
    head1.add(title);
    head1.add("选项标题:");
    head1.add("序号");
    head.add(head1);

    List<String> head11= new ArrayList<>();
    head11.add(title);
    head11.add(content);
    head11.add("姓名");
    head.add(head11);
    List<String> head2 = new ArrayList<>();
    head2.add(title);
    head2.add(content);
    head2.add("房屋信息");
    head.add(head2);
    String bodySrt = " ";
    // 如同意,中立,拒绝
    for (AppVoteOption appVoteOption : appVoteOptions) {
        List<String> headfor = new ArrayList<>();
        headfor.add(title);
        bodySrt = bodySrt+" ";
        headfor.add(bodySrt);
        headfor.add(appVoteOption.getOptionContent());
        head.add(headfor);
    }

    List<String> head5 = new ArrayList<>();
    head5.add(title);
    head5.add(" ");
    head5.add("投票时间");
    head.add(head5);
    //内容
    List<List<String>> bodyList = new ArrayList<>();
    // 序号
    int num = 0;
    for (AppVoteDetailedVO detailedVO : appVoteDetailedVO) {
        List<List<String>>   bodyList2 = new ArrayList<>();
        List<String> body = new ArrayList<>();
        num = num+1;
        body.add(num+"");
        body.add(detailedVO.getUserName());
        body.add(detailedVO.getRoomIdentNo());
        // 表头同意,中立,拒绝 的内容
        for (AppVoteOption appVoteOption : appVoteOptions) {
            // 一样就同意,否者就空
            if (detailedVO.getOptionContent().equals(appVoteOption.getOptionContent())){
                body.add("1");
            }else {
                body.add(" ");
            }

        }
        body.add(detailedVO.getCreateTime());
        bodyList2.add(body);
        bodyList.addAll(bodyList2);
    }

    // 合计统计
    if (appVoteDetailedVO.size()>0){
        List<List<String>>   bodyList2 = new ArrayList<>();
        List<String> body = new ArrayList<>();
        body.add("合计");
        body.add(" ");
        body.add(" ");
        Integer statisticsNum = 0;
        // 数量累加
            for (AppVoteOption appVoteOption : appVoteOptions) {
                for (AppVoteDetailedVO detailedVO : appVoteDetailedVO) {
                if (detailedVO.getOptionContent().equals(appVoteOption.getOptionContent())){
                    statisticsNum =  statisticsNum +1;
                }
            }
            body.add(statisticsNum+"");
            statisticsNum = 0;
        }
        body.add(" ");
        bodyList2.add(body);
        bodyList.addAll(bodyList2);
    }




    // 访问前缀
    String file = HaoNiuConfig.getProfile();
    // 访问地址(返给前端的地址)
    String fileName  = "/" + DateUtils.datePath() + "/" + DateUtils.dateTimeNow() + "_" + title+".xlsx";
    // 全路径
    String fileUrl = file + fileName;
    // 查询文件,不存在就下载
    File desc = new File(fileUrl);
    if (!desc.getParentFile().exists()) {
        desc.getParentFile().mkdirs();
    }
    if (!desc.exists()) {
        try {
            desc.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //创建EXCEL对象
    ExcelWriterBuilder builder = EasyExcel.write(fileUrl);
    //设置处理器,合并单元格,列宽处理器等
    builder.registerWriteHandler(new LongestMatchColumnWidthStyleStrategy());
    //获取writer对象
    ExcelWriter writer= builder.build();
    WriteSheet sheet = EasyExcel.writerSheet(0, title).build();
    // 头的策略
    WriteCellStyle headWriteCellStyle = new WriteCellStyle();
    //
    headWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
    // 字体策略
    WriteFont contentWriteFont = new WriteFont();
    // 字体大小
    contentWriteFont.setFontHeightInPoints((short) 14);
    headWriteCellStyle.setWriteFont(contentWriteFont);
    // 内容的策略
    WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
    contentWriteCellStyle.setWrapped(true);
    contentWriteCellStyle.setBorderLeft(BorderStyle.THIN);
    contentWriteCellStyle.setBorderTop(BorderStyle.THIN);
    contentWriteCellStyle.setBorderRight(BorderStyle.THIN);
    contentWriteCellStyle.setBorderBottom(BorderStyle.THIN);
    HorizontalCellStyleStrategy horizontalCellStyleStrategy =
            new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
    WriteSheet writeSheet = EasyExcel.writerSheet(1, "")
            .registerWriteHandler(horizontalCellStyleStrategy)
            .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
            .head(head)
            .build();

    //写入数据,
    writer.write(bodyList,writeSheet);
    writer.finish();

    // 前端访问地址
    return "profile"+fileName;
}

 

 表头sql

SELECT
    option_content
FROM
    `app_vote_option`
WHERE vote_id = 63
  AND del_flag = 0 

 
 

 

内容

SELECT
    (SELECT
         owner_name
     FROM
         `app_user_community`
     WHERE community_id = a.`community_id`
       AND user_id = a.`user_id`
       AND del_flag = 0) AS userName,
    (SELECT
         room_ident_no
     FROM
         `app_user_community`
     WHERE community_id = a.`community_id`
       AND user_id = a.`user_id`
       AND del_flag = 0) AS roomIdentNo,
    b.option_content AS optionContent,
    a.create_time AS createTime
FROM
    `app_vote_record` AS a
        LEFT JOIN `app_vote_option` AS b
                  ON a.`vote_option_id` = b.`vote_option_id`
                      AND b.`del_flag` = 0
WHERE a.vote_id = #{voteId}
  AND a.del_flag = 0
ORDER BY a.create_time

 

<el-button
  size="mini"
  type="text"
  icon="el-icon-download"
  @click="handleExportDetailed(scope.row)"
>导出</el-button>

前端下载 

 

/** 导出按钮操作 */
handleExportDetailed(row) {
  exportDetailed(row.voteId).then(response => {
    var fileUrl  = process.env.VUE_APP_BASE_API+ response.msg;
    // 创建一个隐藏的<a>元素
    var element = document.createElement('a');
    element.setAttribute('href', fileUrl);
    var lastSlashIndex = fileUrl.lastIndexOf('/');
    var filename = ""
    if (lastSlashIndex !== -1) {
      filename  =   fileUrl.substring(lastSlashIndex + 1);
    }
    element.setAttribute('download', filename);
    // 模拟点击下载
    element.style.display = 'none';
    document.body.appendChild(element);
    element.click();
    document.body.removeChild(element);

  });

},
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
EasyExcel 是一个基于 Java 的 Excel 操作工具,可以用它来读取、写入 Excel 文件。在 EasyExcel 中,实现表头合并可以通过 `@ExcelProperty` 注解的 `index` 属性来实现。 假设我们有一个类 `User`,其中包含了多个属性,如下所示: ```java public class User { @ExcelProperty(value = "姓名", index = 0) private String name; @ExcelProperty(value = "年龄", index = 1) private Integer age; @ExcelProperty(value = "联系方式", index = 2) private String phone; @ExcelProperty(value = "家庭地址", index = 3) private String address; } ``` 在上面的代码中,我们使用了 `@ExcelProperty` 注解来标识 Excel 表头的内容和位置。现在我们想要将“联系方式”和“家庭地址”这两个表头进行合并,可以将它们的 `index` 属性值设为相同的值,如下所示: ```java public class User { @ExcelProperty(value = "姓名", index = 0) private String name; @ExcelProperty(value = "年龄", index = 1) private Integer age; @ExcelProperty(value = {"联系方式", "家庭地址"}, index = 2) private String phoneAndAddress; } ``` 在上面的代码中,我们使用了一个字符串数组来表示合并后的表头,其中第一个元素表示合并后的表头名称,后面的元素表示被合并的原始表头名称。这样,EasyExcel 就会自动将它们进行合并,并生成一个单元格。 需要注意的是,使用 `@ExcelProperty` 注解时,如果要合并表头,需要使用数组来表示表头内容,其中第一个元素表示合并后的表头名称,后面的元素表示被合并的原始表头名称

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值