SpringBoot集成阿里easyexcel(三)自定义EXCEL样式

该博客介绍了如何使用Apache POI库为Excel表格设置全局样式,包括边框、对齐方式、千位分隔符等。同时,通过自定义WriteHandler实现行宽调整,并创建了专门的样式策略来区分表头和内容的样式。最后,在Controller中应用这些样式进行数据导出。
摘要由CSDN通过智能技术生成

Excel表格定义全局样式。
一、使用WriteHandler对行列进行定义

public class ExcelStyleHandler implements WriteHandler {

    @Override
    public void sheet(int i, Sheet sheet) {
    }

    @Override
    public void row(int i, Row row) {
    }

    @Override
    public void cell(int i, Cell cell) {
        //第一行是表头,从第二行开始设置格式
        Workbook workbook = cell.getSheet().getWorkbook();
        CellStyle cellStyle = workbook.createCellStyle();
        //下边框
        cellStyle.setBorderBottom(BorderStyle.THIN);
        //左边框
        cellStyle.setBorderLeft(BorderStyle.THIN);
        //上边框
        cellStyle.setBorderTop(BorderStyle.THIN);
        //右边框
        cellStyle.setBorderRight(BorderStyle.THIN);
        //水平对齐方式
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        //垂直对齐方式
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        if (cell.getRowIndex() > 2) {
              DataFormat dataFormat = workbook.createDataFormat();
              // 设置千位分隔符
              cellStyle.setDataFormat(dataFormat.getFormat("#,##0"));
        }
        cell.getRow().getCell(i).setCellStyle(cellStyle);
    }
}

二、使用AbstractColumnWidthStyleStrategy设置行宽

public class CellWriteHandler extends AbstractColumnWidthStyleStrategy {

    private static final Logger LOGGER = LoggerFactory.getLogger(CellWriteHandler.class);

    private Map<Integer, Map<Integer, Integer>> CACHE = new HashMap<>();

    @Override
    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 = CACHE.get(writeSheetHolder.getSheetNo());
            if (maxColumnWidthMap == null) {
                maxColumnWidthMap = new HashMap<>();
                CACHE.put(writeSheetHolder.getSheetNo(), maxColumnWidthMap);
            }

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

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

            }
        }
    }

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


}

三、使用poi的WriteCellStyle设置头部和内容样式

public class ResourceStatisticsStyleHelper {

    /**
     * 表头样式
     * @return
     */
    public static WriteCellStyle getHeadWriteCellStyle(){
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        headWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        headWriteCellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.index);
        headWriteCellStyle.setBottomBorderColor(IndexedColors.BLACK.index);
        headWriteCellStyle.setLeftBorderColor(IndexedColors.BLACK.index);
        headWriteCellStyle.setRightBorderColor(IndexedColors.BLACK.index);
        headWriteCellStyle.setTopBorderColor(IndexedColors.BLACK.index);
        return headWriteCellStyle;
    }

    /**
     * 内容样式
     * @return
     */
    public static WriteCellStyle getContentWriteCellStyle(){
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
        contentWriteCellStyle.setWrapped(true);
        contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        return contentWriteCellStyle;
    }

}

controller

 // 样式
        WriteCellStyle headWriteCellStyle =  ResourceStatisticsStyleHelper.getHeadWriteCellStyle();
        WriteCellStyle contentWriteCellStyle = ResourceStatisticsStyleHelper.getContentWriteCellStyle();

        //这个策略是 头是头的样式 内容是内容的样式
        HorizontalCellStyleStrategy horizontalCellStyleStrategy =
                new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).build();
        WriteSheet writeSheet = EasyExcel.writerSheet(0, name).head(ProjectExpView.class).registerWriteHandler(horizontalCellStyleStrategy).registerWriteHandler(new CellWriteHandler()).build();
        writeSheet.setAutomaticMergeHead(true);
        excelWriter.write(data, writeSheet);
        excelWriter.finish();
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在Spring Boot项目中集成阿里EasyExcel库,你需要添加相应的依赖项,并编写代码来使用EasyExcel来读写Excel文件。 首先,在你的项目的构建文件(如Maven或Gradle)中添加EasyExcel的依赖项。 如果你使用Maven,可以在`pom.xml`文件中添加以下依赖项: ```xml <dependencies> <!-- EasyExcel --> <dependency> <groupId>com.alibaba</groupId> <artifactId>easyexcel</artifactId> <version>2.4.0</version> </dependency> </dependencies> ``` 如果你使用Gradle,可以在`build.gradle`文件中添加以下依赖项: ```groovy dependencies { // EasyExcel implementation 'com.alibaba:easyexcel:2.4.0' } ``` 接下来,你可以在你的代码中使用EasyExcel来读写Excel文件。下面是一个简单的示例: ```java import com.alibaba.excel.EasyExcel; import com.alibaba.excel.write.builder.ExcelWriterBuilder; import com.alibaba.excel.write.builder.ExcelWriterSheetBuilder; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.ArrayList; import java.util.List; @Controller public class ExcelController { @GetMapping("/export") public void exportExcel(HttpServletResponse response) throws IOException { // 创建数据列表 List<User> userList = new ArrayList<>(); userList.add(new User("张", 20)); userList.add(new User("李四", 25)); userList.add(new User("王五", 30)); // 设置响应头 response.setHeader("Content-Disposition", "attachment; filename=example.xlsx"); response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); // 创建Excel写入器 ExcelWriterBuilder writerBuilder = EasyExcel.write(response.getOutputStream(), User.class); // 创建工作表 ExcelWriterSheetBuilder sheetBuilder = writerBuilder.sheet("Sheet1"); // 写入数据 sheetBuilder.doWrite(userList); // 关闭写入器 writerBuilder.finish(); } // 定义用户实体类 public static class User { private String name; private int age; // 省略构造函数、getter和setter } } ``` 在上面的代码中,我们创建了一个`ExcelController`类,并在其中定义了一个`exportExcel`方法来处理导出Excel的请求。我们使用EasyExcel库创建了Excel写入器,并设置响应头。然后,我们创建了一个工作表,并将数据写入工作表中。最后,我们关闭了写入器。 请注意,上述代码只是一个简单的示例,你可以根据自己的需求进行调整和扩展。确保在项目的依赖中包含了EasyExcel库的相关依赖项。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值