【easyExcel 导出内容自适应】

easyExcel 导出内容自适应

import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.style.column.AbstractColumnWidthStyleStrategy;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Sheet;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CustomCellWriteHandler extends AbstractColumnWidthStyleStrategy {
    private static final int MAX_COLUMN_WIDTH = 255;
    private  Map<Integer, Map<Integer, Integer>> CACHE = new HashMap(8);

    public CustomCellWriteHandler() {
    }

    protected void setColumnWidth(WriteSheetHolder writeSheetHolder, List<CellData> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
        boolean needSetWidth = isHead || !CollectionUtils.isEmpty(cellDataList);
        if (needSetWidth) {
            Map<Integer, Integer> maxColumnWidthMap = (Map)CACHE.get(writeSheetHolder.getSheetNo());
            if (maxColumnWidthMap == null) {
                maxColumnWidthMap = new HashMap(16);
                CACHE.put(writeSheetHolder.getSheetNo(), maxColumnWidthMap);
            }

            Integer columnWidth = this.dataLength(cellDataList, cell, isHead);
            if (columnWidth >= 0) {
                if (columnWidth > 255) {
                    columnWidth = 255;
                }

                Integer maxColumnWidth = (Integer)((Map)maxColumnWidthMap).get(cell.getColumnIndex());
                if (maxColumnWidth == null || columnWidth > maxColumnWidth) {
                    ((Map)maxColumnWidthMap).put(cell.getColumnIndex(), columnWidth);
                    writeSheetHolder.getSheet().setColumnWidth(cell.getColumnIndex(), columnWidth * 256);
                }

            }
        }
    }

    private Integer dataLength(List<CellData> cellDataList, Cell cell, Boolean isHead) {
        if (isHead) {
            return cell.getStringCellValue().getBytes().length;
        } else {
            CellData cellData = (CellData)cellDataList.get(0);
            CellDataTypeEnum type = cellData.getType();
            if (type == null) {
                return -1;
            } else {
                switch(type) {
                    case STRING:
                        return cellData.getStringValue().getBytes().length+6;
                    case BOOLEAN:
                        return cellData.getBooleanValue().toString().getBytes().length+6;
                    case NUMBER:
                        return cellData.getNumberValue().toString().getBytes().length+6;
                    default:
                        return -1;
                }
            }
        }
    }
}

新建测试类

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import javafx.application.Application;
import javafx.stage.Stage;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.dream.pay.report.report.vo.D0RecordModelManagerExcelVo;
import org.springframework.beans.BeanUtils;

import java.io.File;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;

public class Test {
    private final static String path = "F:\\stock\\html\\upload";

    public static void main(String[] args) {
        ExcelWriter writerRTGS = null;
        WriteSheet writeSheetRTGS = null;
        List<D0RecordModelManagerExcelVo> listRTGS = new ArrayList<>();
        File dest = new File(path);
        if (!dest.exists()) {
            dest.mkdirs();
        }
        int index_RTGS = 0;
        StringBuilder localPath = new StringBuilder();
        D0RecordModelManagerExcelVo d0RecordModelManagerExcelVo = new D0RecordModelManagerExcelVo();
        String accountNumber = "62148231231239123919";
        d0RecordModelManagerExcelVo.setAccountNumber( accountNumber);
        d0RecordModelManagerExcelVo.setSnorefno("2023062501");
        String settleAmountString = "1000000000001";
        d0RecordModelManagerExcelVo.setSettleAmountString(settleAmountString);
        d0RecordModelManagerExcelVo.setDescription("settlement");
        d0RecordModelManagerExcelVo.setCity("杭州杭州杭州杭州杭州杭州杭州杭州杭州杭州杭州杭州杭州杭州杭州杭州杭州杭州杭州杭州杭州杭州杭州杭州杭州杭州杭州杭州杭州杭州");
        if (writerRTGS == null) {
            String exportPath = path + "/" + "20230626" + "_RTGS_settlement";
            String fileName = exportPath + ExcelTypeEnum.XLSX.getValue();
            localPath.append(fileName).append(",");
            writerRTGS = EasyExcel.write(fileName, D0RecordModelManagerExcelVo.class).registerWriteHandler(new CustomCellWriteHandler()).build();
            //写第一个sheet,数据全是List<String> 无模型映射关系
            writeSheetRTGS = EasyExcel.writerSheet(1)
                    .registerWriteHandler(getStyleStrategy())
                    .build();
            //设置sheetName
            writeSheetRTGS.setSheetName("20230625" + "_RTGS_settlement");
        }
        String SNO_REF_NO = "20230625";
        index_RTGS++;
        if (index_RTGS < 10) {
            SNO_REF_NO = SNO_REF_NO + "0" + index_RTGS;
        } else {
            SNO_REF_NO = SNO_REF_NO + index_RTGS;
        }

        if (SNO_REF_NO != null) {
            d0RecordModelManagerExcelVo.setSnorefno( SNO_REF_NO);
        }
        listRTGS.add(d0RecordModelManagerExcelVo);
        if (CollectionUtils.isNotEmpty(listRTGS)) {
            writerRTGS.write(listRTGS, writeSheetRTGS);
        }
        writerRTGS.finish();
    }

    /**
     * 表格内容样式
     * @return
     */
    public static HorizontalCellStyleStrategy getStyleStrategy(){
        //表头样式
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        //字体
        WriteFont headWriteFont = new WriteFont();
        headWriteFont.setFontHeightInPoints((short) 11);
        headWriteFont.setBold(true);
        headWriteCellStyle.setWriteFont(headWriteFont);
        //边框
        headWriteCellStyle.setBorderBottom(BorderStyle.THIN);
        headWriteCellStyle.setBorderLeft(BorderStyle.THIN);
        headWriteCellStyle.setBorderRight(BorderStyle.THIN);
        //前景色
        headWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
        //是否换行
        headWriteCellStyle.setWrapped(true);
        headWriteCellStyle.setLocked(true);

        //表体样式
        WriteCellStyle bodyWriteCellStyle = new WriteCellStyle();
        //设置数据格式索引
        bodyWriteCellStyle.setDataFormat((short)49);
        //bodyWriteCellStyle.setWriteFont(headWriteFont);
        //边框
        bodyWriteCellStyle.setBorderBottom(BorderStyle.THIN);
        bodyWriteCellStyle.setBorderLeft(BorderStyle.THIN);
        bodyWriteCellStyle.setBorderRight(BorderStyle.THIN);
        bodyWriteCellStyle.setHidden(true);
        bodyWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        bodyWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        // 设置单引号
        bodyWriteCellStyle.setQuotePrefix(true);
        return new HorizontalCellStyleStrategy(headWriteCellStyle, bodyWriteCellStyle);
    }
}

效果如下
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
easyexcel导出图片自适应的方法如下: 1. 首先,确保你已经添加了easyexcel的依赖。在pom.xml文件中添加以下代码: ```xml <dependency> <groupId>com.alibaba</groupId> <artifactId>easyexcel</artifactId> <version>3.1.1</version> </dependency> ``` 2. 创建一个导出实体类,该实体类中需要包含需要导出的图片字段。例如: ```java @Data @AllArgsConstructor @NoArgsConstructor public class ExcelFeedbackVO extends Feedback { // 其他字段...... @ExcelProperty(value = "图片", index = 4) private String imageUrl; } ``` 3. 修改对外暴露的接口,使其支持导出图片。在`EasyExcel.write()`方法中添加`.registerWriteHandler(new ImageWriteHandler())`,并确保你的`ExcelFeedbackVO`实体类中包含了图片字段。例如: ```java @PostMapping("/downloadBack") public void downloadBack(HttpServletResponse response, String siteId, Integer content) throws TException, IOException { List<Feedback> list = feedbackService.searchBack(siteId, content); setResponse(response, "列表"); EasyExcel.write(response.getOutputStream(), ExcelFeedbackVO.class) .sheet("列表") .registerWriteHandler(new ImageWriteHandler()) // 导出图片 .registerWriteHandler(new CustomCellWriteWidthConfig()) // 自适应列宽 .registerWriteHandler(new CustomCellWriteHeighConfig()) // 自适应行高 .registerWriteHandler(EasyExcelUtils.getStyleStrategy()) // 引用样式 .doWrite(list); } ``` 至此,你已经可以使用easyexcel导出包含图片的Excel,并实现了图片的自适应

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值