余晖落尽暮晚霞,黄昏迟暮远山寻
本站
当前位置:网站首页 > 编程知识 > 正文

还使用POI实现Excel?阿里巴巴Easyexcel来了

xiyangw 2023-10-03 16:25 27 浏览 0 评论

背景

曾几何时,我们总是提心吊胆的使用POI来处理Excel文件,一个3M的文件需要100多兆的内存空间。然而现在我们可以对它Say No,因为阿里巴巴的Easyexcel来了。

Maven坐标

<dependency>
 <groupId>com.alibaba</groupId>
 <artifactId>easyexcel</artifactId>
 <version>2.1.4</version>
</dependency>

示例代码包含以下功能:(1)自定义列宽的实现;(2)单元格字体颜色根据单元格的值动态调整。

public static void downloadExcel(String path, List<List<String>> heads, List<List<Object>> datas) {
 OutputStream outputStream = null;
 try {
  outputStream = new FileOutputStream(path);
  CustomCellStyleStrategy styleStrategy = getStyleStrategy();  // 列宽设置
  CustomColumnWidthStyleStrategy columnWidthStyleStrategy = new CustomColumnWidthStyleStrategy();
  //第一个Sheet
  WriteSheet writeSheet = EasyExcel.writerSheet(0, "信息").head(heads).build();
  // 如果是浏览器下载, 需要设置不关闭流
  ExcelWriter excelWriter = EasyExcel.write(outputStream).autoCloseStream(Boolean.FALSE)
    .excelType(ExcelTypeEnum.XLSX).registerWriteHandler(styleStrategy)
    .registerWriteHandler(columnWidthStyleStrategy).build();
  excelWriter.write(datas, writeSheet);
  excelWriter.finish();
 } catch (Exception e) {
 } finally {
  // 如果是浏览器下载不需要关闭流
  
   IOUtils.closeQuietly(outputStream)
 }
}

参数path是Excel下载地址;heads是列表的头;datas是列表数据;

样式设置

public static CustomCellStyleStrategy getStyleStrategy() {
 //表头样式
 WriteCellStyle headWriteCellStyle = new WriteCellStyle();
 //设置表头居中对齐
 headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER); //背景色
 headWriteCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND); headWriteCellStyle.setFillForegroundColor(IndexedColors.LIGHT_GREEN.getIndex()); // 字体策略
 WriteFont headWriteFont = new WriteFont();
 // 字体大小
 headWriteFont.setFontName("微软雅黑");
 headWriteFont.setBold(true);
 headWriteFont.setFontHeightInPoints((short) 10);
 headWriteCellStyle.setWriteFont(headWriteFont); //设置 自动换行
 // headWriteCellStyle.setWrapped(true);
 //设置 垂直居中
 headWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER); //内容样式
 WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
 //设置内容靠居中对齐
 contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER); contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER); WriteFont contentWriteFont = new WriteFont();
 // 字体大小
 contentWriteFont.setFontName("微软雅黑");
 contentWriteFont.setBold(false);
 contentWriteFont.setFontHeightInPoints((short) 9);
 contentWriteCellStyle.setWriteFont(contentWriteFont); contentWriteCellStyle.setWrapped(true);
 CustomCellStyleStrategy horizontalCellStyleStrategy = new CustomCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
 return horizontalCellStyleStrategy;
}

CustomCellStyleStrategy单元格字体颜色动态调整

public class CustomCellStyleStrategy extends AbstractCellStyleStrategy {
    private WriteCellStyle headWriteCellStyle;
    private WriteCellStyle contentWriteCellStyle;
    private CellStyle headCellStyle;
    public CustomCellStyleStrategy(WriteCellStyle headWriteCellStyle, WriteCellStyle contentWriteCellStyle) {
        this.headWriteCellStyle = headWriteCellStyle;
        this.contentWriteCellStyle = contentWriteCellStyle;
    }    protected void initCellStyle(Workbook workbook) {
        if (this.headWriteCellStyle != null) {
            this.headCellStyle = StyleUtil.buildHeadCellStyle(workbook, this.headWriteCellStyle);
        }    }    protected void setHeadCellStyle(Cell cell, Head head, Integer relativeRowIndex) {
        if (this.headCellStyle != null) {
            cell.setCellStyle(this.headCellStyle);
        }    }    protected void setContentCellStyle(Cell cell, Head head, Integer relativeRowIndex) {
    }    private void setContentCellStyle(WriteSheetHolder writeSheetHolder, Cell cell, Head head, Integer relativeRowIndex) {
        Workbook workbook = writeSheetHolder.getSheet().getWorkbook();        WriteFont contentWriteFont = new WriteFont();
        // 字体大小
        contentWriteFont.setFontName("微软雅黑");
        contentWriteFont.setBold(false);
        contentWriteFont.setFontHeightInPoints((short) 9);
        int columIndex = cell.getColumnIndex();
        String value = cell.getStringCellValue();
        double doubleValue = Double.parseDouble(value);
        if (doubleValue < 0.0) {
            contentWriteFont.setColor(IndexedColors.GREEN.getIndex());
        } else {
            contentWriteFont.setColor(IndexedColors.RED.getIndex());
        }
        contentWriteCellStyle.setWriteFont(contentWriteFont);
        CellStyle cellStyle = StyleUtil.buildContentCellStyle(workbook, contentWriteCellStyle);
        cell.setCellStyle(cellStyle);
    }
    public void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, List<CellData> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
        if (isHead != null && head != null) {
            if (isHead.booleanValue()) {
                this.setHeadCellStyle(cell, head, relativeRowIndex);
            } else {
                this.setContentCellStyle(writeSheetHolder, cell, head, relativeRowIndex);
            }
        }
    }
}

CustomColumnWidthStyleStrategy列宽设置

public class CustomColumnWidthStyleStrategy extends AbstractColumnWidthStyleStrategy {
    protected void setColumnWidth(WriteSheetHolder writeSheetHolder,
                                  List<CellData> cellDataList, Cell cell,
                                  Head head, Integer relativeRowIndex, Boolean isHead) {
        if (!isHead) {
            return;
        }        int columIndex = cell.getColumnIndex();
        // 设置列的宽度
        writeSheetHolder.getSheet().setColumnWidth(columIndex,
                ColumnEnum.getWidthByIndex(columIndex));
    }
}

ColumnEnum枚举类,只有核心代码,其余代码自己补齐

COLUMN_0(0, "字段1", 8 * 256),
COLUMN_1(1, "字段2", 10 * 256);
public static int getWidthByIndex(int index) {
 for (ColumnEnum item : ColumnEnum.values()) {
  if (item.index == index) {
   return item.width;
  } } return 10 * 256;
}

数据构造

public static void main(String[] args) {
 String path = "D:/export/test.xlsx";
 List<List<String>> heads = new ArrayList<>();
 heads.add(Arrays.asList("字段1"));
 heads.add(Arrays.asList("字段2"));
 List<List<Object>> datas = new ArrayList<>();
 List<Object> rows1 = Arrays.asList("1", "-1");
 datas.add(rows1); List<Object> rows2 = Arrays.asList("-2", "2");
 datas.add(rows2); 
  downloadExcel(path, heads, datas);
}

Excel输出结果,单元格中的数字大于等于0的为红色,小于0的为绿色

相关推荐

华为交换机配置命令总结

1、配置文件相关命令[Quidway]displaycurrent-configuration显示当前生效的配置[Quidway]displaysaved-configuration显示fla...

解决账户无法登录的故障
解决账户无法登录的故障

在优化系统时错误地根据网上的提示,将唯一的Administrator账户设置为禁用,导致重启后无法进入系统。类似的故障还有使用组策略限制本地账户登录,导致重启后...

2023-10-11 17:16 xiyangw

S5720交换机登录提示初始密码存在安全风险
S5720交换机登录提示初始密码存在安全风险

问题描述客户每次登录输密码时,提示初始密码不安全,现在客户嫌麻烦想要去掉:Username:huaweiPassword:Warning:Theinitia...

2023-10-11 17:15 xiyangw

Springboot,Mybatis修改登录用户的密码
Springboot,Mybatis修改登录用户的密码

一、Mybatis.xml<updateid="changePassword"parameterType="string...

2023-10-11 17:15 xiyangw

PHP理论知识之沐浴更衣重看PHP基础(二)
PHP理论知识之沐浴更衣重看PHP基础(二)

接上篇,咱们继续讲解PHP基础八、标准PHP组件和框架的数量很多,随之产生的问题就是:单独开发的框架没有考虑到与其他框架的通信。这样对开发者和框架本身都是不利的...

2023-10-11 17:15 xiyangw

新鲜出炉UCloud云主机“数据方舟”评测报告(5)— — 关其城
新鲜出炉UCloud云主机“数据方舟”评测报告(5)— — 关其城

2015年10月29日,UCloud云主机黑科技——“数据方舟”功能正式上线,首轮内测随即开放。截止至2015年12月6日,我们共收到了534位用户的评测申...

2023-10-11 17:14 xiyangw

业余无线电Q简语及英文缩语
业余无线电Q简语及英文缩语

Q简语:语音通信及CW通信通用(加粗为常用)QRA电台何台QRB电台间之距离QRG告之正确频率QRH频率是否变动QRI发送音调QRJ能否收到QRK信号之可...

2023-10-11 17:14 xiyangw

非常详细!如何理解表格存储的多版本、生命周期和有效版本偏差
非常详细!如何理解表格存储的多版本、生命周期和有效版本偏差

表格存储在8月份推出了容量型实例,直接支持了表级别最大版本号和生命周期,高性能实例也将会在9月中旬支持这两个特性。那么,最大版本号和生命周期以及特有的...

2023-10-11 17:14 xiyangw

H3C交换机恢复出厂和各种基本配置,这20个要点你知道吗?
H3C交换机恢复出厂和各种基本配置,这20个要点你知道吗?

私信“干货”二字,即可领取138G伺服与机器人专属及电控资料!H3C交换机不知道密码如何恢复出厂设置1、开机启动,Ctrl+B进入bootrom菜单,选择恢复出...

2023-10-11 17:13 xiyangw

在使用移动支付系统的时候如何保护信息安全?

移动支付的方式近年来不断被更新,使得Venmo(据嘉丰瑞德理财师了解,此为美国的“支付宝”)之类的支付方式已经可以某种意义上代替随身携带现金了。但是你必须防范那些第三方应用程序轻松地获取你的银行卡以及...

界面控件DevExpress WinForms MVVM入门指南——登录表单(下)

从本文档中,您将了解如何向应用程序添加登录表单。在本节教程中着重讨论了如何实现此任务,这基本上是附加应用程序功能的一部分。DevExpressUniversalSubscription官方最新版免...

linux基础命令(一)
linux基础命令(一)

为啥要学linux?您可能熟悉WindowsXP、Windows7、Windows10和MacOSX等操作系统。Linux就是这样一种强大的操...

2023-10-11 17:13 xiyangw

MySQL数据库密码忘记了,怎么办?

#头条创作挑战赛#MySQL数据库密码忘记了且没有其他可以修改账号密码的账户时怎么办呢?登录MySQL,密码输入错误/*密码错误,报如下错误*/[root@TESTDB~]#mysql-u...

MobaXterm忘记Session密码,如何查看已保存的密码
MobaXterm忘记Session密码,如何查看已保存的密码

MobaXterm工具登录过SSH终端后,如果存储了Session(存储后再连接ssh的时候只需要输入账号不需要输入密码就可以直接连接上ssh),则可以...

2023-10-11 17:12 xiyangw

华为交换机密码丢失修改方法
华为交换机密码丢失修改方法

华为S2300交换机找回密码设置一、目的交换机的console和telnet密码丢失,无法登录设备。交换机已进行过数据配置,要把密码恢复而数据配置不能丢失。二、...

2023-10-11 17:12 xiyangw

取消回复欢迎 发表评论: