ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

【easyExcel】easyExcel自定义单元格

2022-02-23 15:31:46  阅读:251  来源: 互联网

标签:cellLockStyle 自定义 easyExcel 单元格 cell columnIndexs dropDownMap new annotationsMap


easyExcel自定义单元格

配置

依赖

 <!-- https://mvnrepository.com/artifact/com.alibaba/easyexcel -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>easyexcel</artifactId>
            <version>2.2.11</version>
        </dependency>

对象

@Data
@Accessors(chain = true)
@HeadFontStyle(fontName = "等线", fontHeightInPoints = 10)
public class ApproveList {

    @ExcelProperty(value = "approveResult",index = 0)
    private String approveResult;

    private String remark;

    private String id;

    private String pn;

    private String detail;
 }

写excel

导出excel方法

public void download(HttpServletResponse response,ApproveList approveList){
       String fileName =
                URLEncoder.encode(
                        ("ApproveList"  + dateFormat.format(new Date())), "UTF-8");

        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        
        //设置approveResult为下拉选择框,设置选择框的枚举值
        approveList.getApproveResult();
        HashMap<Integer, String[]> dropDownMap = new HashMap<>();
        dropDownMap.put(0,new String[]{"Approve","Reject"});

        //设置哪些列不可编辑,字段索引
        List<Integer> columnIndex = new ArrayList<>();
        for (int i = 2; i < 4; i++) {
            columnIndex.add(i);
        }

        try {
            EasyExcel.write(response.getOutputStream(), ApproveList.class).
                    registerWriteHandler(new CustomCellWriteHandler())
                    .registerWriteHandler(new ContentCellWriteHandler(columnIndex,dropDownMap))
                    .sheet("ApproveList").doWrite(approveList);
        } catch (IOException e) {
            e.printStackTrace();
        }
}

实现CellWriteHandler接口

public class ContentCellWriteHandler implements CellWriteHandler {

    private List<Integer> columnIndexs;
    private Short colorIndex;
    private HashMap<Integer,String> annotationsMap;
    private HashMap<Integer,String[]> dropDownMap;

    public ContentCellWriteHandler(List<Integer> columnIndexs, Short colorIndex, HashMap<Integer,String> annotationsMap){
        this.columnIndexs=columnIndexs;
        this.colorIndex=colorIndex;
        this.annotationsMap=annotationsMap;
    }

    public ContentCellWriteHandler(List<Integer> columnIndexs, Short colorIndex, HashMap<Integer,String> annotationsMap, HashMap<Integer,String[]> dropDownMap){
        this.columnIndexs=columnIndexs;
        this.colorIndex=colorIndex;
        this.annotationsMap=annotationsMap;
        this.dropDownMap=dropDownMap;
    }

    public ContentCellWriteHandler(List<Integer> columnIndexs, HashMap<Integer,String[]> dropDownMap){
        this.columnIndexs=columnIndexs;
        this.dropDownMap=dropDownMap;
    }

    @Override
    public void beforeCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row, Head head, Integer integer, Integer integer1, Boolean aBoolean) {}

    @Override
    public void afterCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Cell cell, Head head, Integer integer, Boolean aBoolean) {}

    @Override
    public void afterCellDataConverted(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, CellData cellData, Cell cell, Head head, Integer integer, Boolean aBoolean) {}

    @Override
    public void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, List<CellData> list, Cell cell, Head head, Integer integer, Boolean isHead) {
        if (!isHead){
            Sheet sheet = writeSheetHolder.getSheet();

            if (CollectionUtils.isNotEmpty(columnIndexs)){
                Workbook workbook = sheet.getWorkbook();
//                CellStyle cellStyle1 = StyleUtil.buildHeadCellStyle(workbook, writeFont);
                /* 这里要重新create不锁定的列样式 */
                CellStyle unlockCellStyle = workbook.createCellStyle();
                unlockCellStyle.setLocked(false);//默认是锁定状态;将所有单元格设置为:未锁定;然后再对需要上锁的单元格单独锁定
                cell.setCellStyle(unlockCellStyle);
                if (colorIndex != null && columnIndexs.contains(cell.getColumnIndex())){
                    WriteCellStyle writeCellStyle = new WriteCellStyle();
                    WriteFont writeFont = new WriteFont();
                    writeFont.setColor(colorIndex);
                    writeCellStyle.setWriteFont(writeFont);
                }
                /* 这里可以根据需要进行判断;我这就将columnIndexs列上锁了 */
                if (cell.getColumnIndex() != 1 && columnIndexs.contains(cell.getColumnIndex())){
                    // 设置表单保护密码
                    writeSheetHolder.getSheet().protectSheet("password");
                    // 设置锁定单元格
//                    CellStyle cellLockStyle = StyleUtil.buildHeadCellStyle(workbook, writeFont);
                    /*  这里要重新create列锁定的列样式,*/
                    CellStyle cellLockStyle = workbook.createCellStyle();
                    cellLockStyle.setLocked(true);
                    cellLockStyle.setVerticalAlignment(VerticalAlignment.CENTER);
                    cellLockStyle.setFillBackgroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
                    cellLockStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
                    cellLockStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
                    cellLockStyle.setBorderBottom(BorderStyle.THIN);
                    cellLockStyle.setBorderTop(BorderStyle.THIN);
                    cellLockStyle.setBorderLeft(BorderStyle.THIN);
                    cellLockStyle.setBorderRight(BorderStyle.THIN);
                    cellLockStyle.setWrapText(true);
                    cell.setCellStyle(cellLockStyle);
                }

            }
            if (annotationsMap != null && annotationsMap.containsKey(cell.getColumnIndex())){
                String context = annotationsMap.get(cell.getColumnIndex());
                Comment cellComment =sheet.createDrawingPatriarch().createCellComment(new XSSFClientAnchor(0, 0, 0, 0, (short) cell.getColumnIndex(), 0, (short) 5, 5));
                cellComment.setString(new XSSFRichTextString(context));
                cell.setCellComment(cellComment);
            }
            //设置下拉框
            if (dropDownMap !=null && dropDownMap.containsKey(cell.getColumnIndex())){
                String[] datas = dropDownMap.get(cell.getColumnIndex());
                DataValidationHelper dataValidationHelper = sheet.getDataValidationHelper();
                DataValidationConstraint dvConstraint = dataValidationHelper.createExplicitListConstraint(datas);
                CellRangeAddressList addressList = null;
                DataValidation validation = null;
                for (int i = 1; i < 1000; i++) {
                    addressList = new CellRangeAddressList(i, i, cell.getColumnIndex(), cell.getColumnIndex());
                    validation = dataValidationHelper.createValidation(
                            dvConstraint, addressList);
                    sheet.addValidationData(validation);
                }
            }
        }
    }
}
  • cellLockStyle.setLocked(true);设置为不可编辑,但导出后发现所有单元格均不可编辑:
    • 因为createCell();创建单元格后,单元格默认是锁定状态;
    • protectSheet(“密码”);保护工作表是保护所有锁定的单元格;

导出效果:
在这里插入图片描述

读excel

对象中设置@Accessors(chain = true),easyExcel能读取行数据,但是解析不了,也就是映射不了相应的类。

标签:cellLockStyle,自定义,easyExcel,单元格,cell,columnIndexs,dropDownMap,new,annotationsMap
来源: https://blog.csdn.net/weixin_37838913/article/details/123090290

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有