Java POI excel单元格背景色(填充)、字体颜色(对齐)、边框(颜色)、行高、列宽设置

news2024/10/7 7:32:38

文章目录

  • 1、Excel Cell单元格背景色+颜色名称对照关系
  • 2、Excel Cell单元格背景填充样式+颜色填充对照关系
  • 3、Excel Cell字体样式设置+对照图
  • 4、Excel 行高、列宽设置
  • 5、Excel单元格边框设置+边框类型图片对比
  • 附一:一些问题
    • 1、关于列宽使用磅*20的计算方式
    • 2、关于行高使用磅*256+185的计算方式
    • 3、关于sheet.getLastRowNum()最终行数不正确问题
    • 4、IDEA中按住快捷键(Shift)+鼠标悬浮到对应单词可以查看颜色
  • 附二:参考链接

需要的Maven环境配置

    <!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
    <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi</artifactId>
      <version>5.2.2</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
    <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi-ooxml</artifactId>
      <version>5.2.2</version>
    </dependency>

部分需要注意的问题,通过注释的方式写在代码里面了,看代码的时候需要注意下注释

1、Excel Cell单元格背景色+颜色名称对照关系

    /**
     * 设置单元格背景颜色
     * <pre>
     *     像素、磅、点、缇等各种单位换算参考链接
     *          https://blog.csdn.net/tanghuan/article/details/113539369
     *     Excel Cell设置背景颜色参考链接
     *          https://blog.csdn.net/weixin_43845227/article/details/123580523
     *     Excel POI Cell背景颜色对照关系表参考链接
     *          https://blog.csdn.net/lenovo96166/article/details/102765781
     *          https://www.cnblogs.com/quchunhui/p/14378115.html
     *     Excel Cell POI Width宽度设置公式参考链接(拟合方程)
     *          https://blog.csdn.net/duqian42707/article/details/51491312
     *          https://blog.csdn.net/aosica321/article/details/72320050
     * </pre>
     */
    public static void setBackgroundColorCellStyle() throws IOException {
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("excel样式设置");

        int rowIndex = 0;
        for (IndexedColors color : IndexedColors.values()) {
            short colorIndex = color.getIndex();

            HSSFCellStyle cell1Style = workbook.createCellStyle();
            // 设置的背景颜色
            cell1Style.setFillForegroundColor(colorIndex);
            // 填充效果(全景填充)
            cell1Style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
            cell1Style.setAlignment(HorizontalAlignment.CENTER);
            cell1Style.setVerticalAlignment(VerticalAlignment.CENTER);

            HSSFRow row = sheet.createRow(rowIndex++);
            row.setHeight((short) (25 * 20));
            // 第一列
            HSSFCell cell1 = row.createCell(0);
            cell1.setCellStyle(cell1Style);
            cell1.setCellValue("X:" + colorIndex);

            // 第二列
            HSSFCellStyle cell2Style = workbook.createCellStyle();
            cell2Style.setAlignment(HorizontalAlignment.CENTER);
            cell2Style.setVerticalAlignment(VerticalAlignment.CENTER);

            HSSFCell cell2 = row.createCell(1);
            cell2.setCellStyle(cell2Style);
            cell2.setCellValue(color.name());
            // 设置列宽
            sheet.setColumnWidth(0, 10 * 256 + 185);
            sheet.setColumnWidth(1, 35 * 256 + 185);
        }

        FileOutputStream outputStream = new FileOutputStream("D:/temp/Excel背景颜色列表.xlsx");
        workbook.write(outputStream);
        outputStream.close();
        workbook.close();
    }

image.pngimage.pngimage.png

2、Excel Cell单元格背景填充样式+颜色填充对照关系

    /**
     * 设置背景颜色填充效果
     * <pre>
     *      背景颜色填充效果参考链接
     *          https://blog.csdn.net/qq_39541254/article/details/107940224
     * </pre>
     */
    public static void setFillBackgroundColor() throws IOException {
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("excel填充设置");

        int rowIndex = 0;
        short colorIndex = IndexedColors.RED.getIndex(); // 选择红色(可参照上图背景色色号) --> 10

        // 填充样式
        for (FillPatternType patternType : FillPatternType.values()) {
            HSSFCellStyle cell1Style = workbook.createCellStyle();
            // 设置的背景颜色
            cell1Style.setFillForegroundColor(colorIndex);
            // 填充效果(全景填充)
            cell1Style.setFillPattern(patternType);
            // 设置垂直居中
            cell1Style.setAlignment(HorizontalAlignment.CENTER);
            cell1Style.setVerticalAlignment(VerticalAlignment.CENTER);
            // 设置字体
            HSSFFont font = workbook.createFont();
            // 加粗
            font.setBold(true);
            cell1Style.setFont(font);

            HSSFRow row = sheet.createRow(rowIndex++);
            // 设置行高:height = 磅 * 20 (1磅=0.353毫米=20缇)-> POI中行高是"缇(twips)"
            row.setHeight((short) (25 * 20));
            // 第一列
            HSSFCell cell1 = row.createCell(0);
            cell1.setCellStyle(cell1Style);
            cell1.setCellValue("code:" + patternType.getCode());

            HSSFCellStyle cell2Style = workbook.createCellStyle();
            // 设置垂直居中
            cell2Style.setAlignment(HorizontalAlignment.CENTER);
            cell2Style.setVerticalAlignment(VerticalAlignment.CENTER);
            // 第二列
            HSSFCell cell2 = row.createCell(1);
            cell2.setCellStyle(cell2Style);
            cell2.setCellValue(patternType.name());

            // 设置列宽: width = 256*磅 + 185
            sheet.setColumnWidth(0, 10 * 256 + 185);
            sheet.setColumnWidth(1, 24 * 256 + 185);
        }

        FileOutputStream outputStream = new FileOutputStream("D:/temp/Excel背景填充效果.xlsx");
        workbook.write(outputStream);
        outputStream.close();
        workbook.close();
    }

image.pngimage.png

3、Excel Cell字体样式设置+对照图

    /**
     * 设置单元格字体样式
     */
    public static void setCellFontStyle() throws IOException {
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("excel字体样式");

        HSSFCellStyle cellStyle = workbook.createCellStyle();
        HSSFFont font = workbook.createFont();
        // 字体加粗
        font.setBold(true);
        // 字体倾斜
        font.setItalic(true);
        // 字体删除线
        font.setStrikeout(true);
        // 字体颜色
        font.setColor(IndexedColors.YELLOW.getIndex());
        // 字体大小:字号
        font.setFontHeightInPoints((short) 14);
        // 设置行高
        // font.setFontHeight((short) 14);
        // 字体
        font.setFontName("宋体");
        cellStyle.setFont(font);

        // 设置文字垂直居中
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        // 设置单元格内容自动换行(文字超出列宽自动换行)
        cellStyle.setWrapText(true);


        HSSFRow row = sheet.createRow(0);
        HSSFCell cell = row.createCell(0);
        cell.setCellStyle(cellStyle);
        cell.setCellValue("字体");

        row.setHeight((short) (30 * 20));
        sheet.setColumnWidth(0, 30 * 256 + 185);


        FileOutputStream outputStream = new FileOutputStream("D:/temp/Excel字体样式.xlsx");
        workbook.write(outputStream);
        outputStream.close();
        workbook.close();
    }

image.pngimage.png

4、Excel 行高、列宽设置

    /**
     * 行高列宽设置
     */
    public static void setRowHeightAndCellWidth() throws IOException {
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("excel行高、列宽");
        // 定义一个5行、5列的数据
        int[][] data = {{1, 2, 3, 4, 5}, {6, 7, 8, 9, 10}, {11, 12, 13, 14, 15}, {16, 17, 18, 19, 20}, {21, 22, 23, 24, 25}};

        for (int rowIndex = 0; rowIndex < data.length; rowIndex++) {
            int[] cellData = data[rowIndex];

            HSSFRow row = sheet.createRow(rowIndex);
            // 行高计算方式:缇(twips) = 磅 * 20 ==> 换算 1磅=20缇
            row.setHeight((short) (25 * 20));
            for (int cellIndex = 0; cellIndex < cellData.length; cellIndex++) {
                HSSFCell cell = row.createCell(cellIndex);
                // 列宽计算方式:8磅 * 256 + 185
                sheet.setColumnWidth(cellIndex, 8 * 256 + 185);
                cell.setCellValue(cellData[cellIndex]);
            }
        }

        FileOutputStream outputStream = new FileOutputStream("D:/temp/Excel行高、列宽.xlsx");
        workbook.write(outputStream);
        outputStream.close();
        workbook.close();
    }

image.png

5、Excel单元格边框设置+边框类型图片对比

    /**
     * 设置多有边框样式 + 颜色
     */
    public static void setAllBorderStyle() throws IOException {
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("excel单元格边框样式");

        // ======================= 设置边框
        int rowIndex = 0;
        for (BorderStyle borderStyle : BorderStyle.values()) {
            int cellIndex = 0;
            HSSFRow row = sheet.createRow(rowIndex++);
            row.setHeight((short) (35 * 20));
            // 第一列
            HSSFCell cell = row.createCell(cellIndex);
            HSSFCellStyle topBorderStyle = workbook.createCellStyle();
            // 上边框样式
            topBorderStyle.setBorderTop(borderStyle);
            cell.setCellValue("设置上边框(" + borderStyle.name() + ")");
            cell.setCellStyle(topBorderStyle);
            sheet.setColumnWidth(cellIndex, 35 * 256 + 185);

            cellIndex += 2;
            // 第三列
            HSSFCell cell2 = row.createCell(cellIndex);
            HSSFCellStyle bottomBorderStyle = workbook.createCellStyle();
            // 下边框样式
            bottomBorderStyle.setBorderBottom(borderStyle);
            cell2.setCellValue("设置下边框(" + borderStyle.name() + ")");
            cell2.setCellStyle(bottomBorderStyle);
            sheet.setColumnWidth(cellIndex, 35 * 256 + 185);

            cellIndex += 2;
            // 第五列
            HSSFCell cell3 = row.createCell(cellIndex);
            HSSFCellStyle leftBorderStyle = workbook.createCellStyle();
            // 左边框样式
            leftBorderStyle.setBorderLeft(borderStyle);
            cell3.setCellValue("设置左边框(" + borderStyle.name() + ")");
            cell3.setCellStyle(leftBorderStyle);
            sheet.setColumnWidth(cellIndex, 35 * 256 + 185);

            cellIndex += 2;
            // 第七列
            HSSFCell cell4 = row.createCell(cellIndex);
            HSSFCellStyle rightBorderStyle = workbook.createCellStyle();
            // 左边框样式
            rightBorderStyle.setBorderRight(borderStyle);
            cell4.setCellValue("设置右边框(" + borderStyle.name() + ")");
            cell4.setCellStyle(rightBorderStyle);
            sheet.setColumnWidth(cellIndex, 35 * 256 + 185);
        }

        // ================= 设置边框并设置颜色
        rowIndex += 2;
        for (BorderStyle borderStyle : BorderStyle.values()) {
            int cellIndex = 0;
            HSSFRow row = sheet.createRow(rowIndex++);
            row.setHeight((short) (35 * 20));
            // 第一列
            HSSFCell cell = row.createCell(cellIndex);
            HSSFCellStyle topBorderStyle = workbook.createCellStyle();
            // 上边框样式
            topBorderStyle.setBorderTop(borderStyle);
            // 上边框颜色
            topBorderStyle.setTopBorderColor(IndexedColors.RED.getIndex());
            cell.setCellValue("设置上边框(" + borderStyle.name() + ")");
            cell.setCellStyle(topBorderStyle);
            sheet.setColumnWidth(cellIndex, 35 * 256 + 185);

            cellIndex += 2;
            // 第三列
            HSSFCell cell2 = row.createCell(cellIndex);
            HSSFCellStyle bottomBorderStyle = workbook.createCellStyle();
            // 下边框样式
            bottomBorderStyle.setBorderBottom(borderStyle);
            // 下边框颜色
            bottomBorderStyle.setBottomBorderColor(IndexedColors.GREEN.getIndex());
            cell2.setCellValue("设置下边框(" + borderStyle.name() + ")");
            cell2.setCellStyle(bottomBorderStyle);
            sheet.setColumnWidth(cellIndex, 35 * 256 + 185);

            cellIndex += 2;
            // 第五列
            HSSFCell cell3 = row.createCell(cellIndex);
            HSSFCellStyle leftBorderStyle = workbook.createCellStyle();
            // 左边框样式
            leftBorderStyle.setBorderLeft(borderStyle);
            // 左边框颜色
            leftBorderStyle.setLeftBorderColor(IndexedColors.YELLOW.getIndex());
            cell3.setCellValue("设置左边框(" + borderStyle.name() + ")");
            cell3.setCellStyle(leftBorderStyle);
            sheet.setColumnWidth(cellIndex, 35 * 256 + 185);

            cellIndex += 2;
            // 第七列
            HSSFCell cell4 = row.createCell(cellIndex);
            HSSFCellStyle rightBorderStyle = workbook.createCellStyle();
            // 左边框样式
            rightBorderStyle.setBorderRight(borderStyle);
            // 右边框颜色
            rightBorderStyle.setRightBorderColor(IndexedColors.ORANGE.getIndex());
            cell4.setCellValue("设置右边框(" + borderStyle.name() + ")");
            cell4.setCellStyle(rightBorderStyle);
            sheet.setColumnWidth(cellIndex, 35 * 256 + 185);
        }

        FileOutputStream outputStream = new FileOutputStream("D:/temp/Excel单元格边框样式.xlsx");
        workbook.write(outputStream);
        outputStream.close();
        workbook.close();
    }

边框样式对照表,括号内为BorderStyle枚举对象

在这里插入图片描述

附一:一些问题

1、关于列宽使用磅*20的计算方式

image.png

2、关于行高使用磅*256+185的计算方式

image.png

3、关于sheet.getLastRowNum()最终行数不正确问题

image.png
如果整个Excel中存在空行(整行空),当时若干空行下面存在其他数据,这时候获取到的最终行号就不对了,尤其是存在合并单元格的情况最容易出现这类问题。
image.png
很明显10、11、13、14全都是空行了,这时候的lastNum就是不正确的,这种情况要尤为注意。

避免这种情况的出现最直接的一种方式就是,预先知道数据存在多少行,先把所有行都生成sheet.createRow(0)。


同样地,空白的单元格也会出现这种情况,如果单元格不存在或没有样式,获取到的最后一个单元格列数也是不正确的。

4、IDEA中按住快捷键(Shift)+鼠标悬浮到对应单词可以查看颜色

在这里插入图片描述
在这里插入图片描述

附二:参考链接

像素、磅、点、缇等各种单位换算_点和像素换算_tanghuan的博客-CSDN博客
JAVA对excle创建、读取、设置单元格颜色、背景色、跨行跨列_java设置excel背景色_谷同学的博客-CSDN博客
POI4颜色名称,颜色汉语名称,颜色对应关系_软件工程师文艺的博客-CSDN博客
POI设置Excel单元格背景色(setFillForegroundColor与setFillPattern的使用) - 大墨垂杨 - 博客园
java用POI设置Excel的列宽_sheet.setcolumnwidth_duqian42707的博客-CSDN博客
Java POI 设置Excel单元格的宽度和高度_java poi 设置单元格宽度_aosica的博客-CSDN博客

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/726865.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

常用数据预处理与特征选择方法总结记录

在很多机器学习或者是深度学习建模之前&#xff0c;对于数据的处理尤为重要&#xff0c;选择合适的数据预处理方法和特征构建算法对于后续模型的结果有着很大的影响作用&#xff0c;这里的主要目的就是想记录总结汇总常用到的处理方法&#xff0c;学习备忘&#xff01; 数据清洗…

Docker集群部署-MySQL主从复制

实验目的 利用Docker实现MySQL主从复制架构的部署&#xff0c;实现1主1从集群配置。 实验准备 要求实验主机能够连接外网&#xff0c;已经正确安装Docker&#xff0c;并关闭防火墙和selinux。 【实验步骤】 新建主服务器容器实例3307 # docker run -p 3307:3306 --name my…

mysql —案例复杂查询+索引使用+DBeaver中创建索引

前言 接上章 我们 对一个简单的选课功能进行 设计分析 实际上在工作中 拿到一个需求&#xff0c;也是这样的一个分析过程 一个份 需求文档原型 出来&#xff0c;只要是你负责这个模块&#xff0c;就需要你自己建表建库&#xff0c;设计接口文档&#xff0c;也许现在有的公司…

AIGC|FineTune工程之LoRa高效参数微调

徐辉 | 后端开发工程师 一、引言 随着深度学习和自然语言处理技术的快速发展&#xff0c;大型预训练语言模型&#xff08;如GPT、Vicuna、Alpaca、Llama、ChatGLM等&#xff09;在各种应用场景中取得了显著的成果。然而&#xff0c;从零开始训练这些模型需要大量的计算资源和…

Cristiano Linux学习小结

一、linux基础 1.1 基本概述 1、Linux组成&#xff1a;内核 Shell 文件系统 应用程序 2、内核&#xff08;Kernel&#xff09;&#xff0c;即核心程序。实现操作系统的基本功能(进程管理、内存管理、进程间通信、虚拟文件系统和网络接口)&#xff0c;决定着系统的性能和稳定性。…

递归典型例题:汉诺塔问题

文章目录 1. 什么是汉诺塔2. 汉诺塔的解题步骤3. 代码实现汉诺塔 1. 什么是汉诺塔 1. 汉诺塔的来源 一位法国数学家曾编写过一个印度的古老传说&#xff1a;在世界中心拿勒斯的圣庙里边&#xff0c;有一块黄铜板&#xff0c;上边插着三根宝柱。印度教的主神梵天在创造世界的时…

div绑定键盘点击事件

为箭头绑定绑定键盘方向键 <div class"toggle-nav"><spanv-if"leftToggleSt"click"toggleGoods(1)"keyup.left"toggleGoods(1)"class"toggle-left"><a-icon type"left" class"icon" /&…

Linux系统设置

Linux的系统设置 01 选择“Install CentOS7” 02 选择安装界面的语言 03 选择时区&#xff0c;这里选择上海 04 选择安装类型&#xff0c;选择最小安装即可&#xff0c;不需要图形界面与其他的组件 05 选择安装位置&#xff0c;自定义分区 06 我要配置分区&#xff0c;进行…

ARS408毫米波雷达使用记录

参考&#xff1a;ARS_408毫米波雷达数据解析学习记录 感谢博主的分享&#xff08;https://blog.csdn.net/weixin_49401384&#xff09; 雷达can消息解析&#xff08;通用can解析思路&#xff09; socketcan学习can总线 毫米波雷达can协议解读RadarCfgRadarState 代码基本是关于…

Python接口自动化核心模块 - 数据库操作和日志

进行接口测试时&#xff0c;我们需要连接到数据库中&#xff0c;对数据源进行备份、还原、验证等操作。 Python连接数据库常见模块 MysqlDB python2时代最火的驱动库。基于C开发&#xff0c;对windows平台不友好。现在已经进入python3时代&#xff0c;基本不再使用 MysqlCl…

干农活太累了,尤其是对一位22女孩来说

干农活太累了&#xff0c;尤其是对一位22女孩来说。要是能够通过电商来销售农产品可以大大减轻干农活的负担。在重庆荣昌的一个小村庄里&#xff0c;一个名叫杨儿杨的00后女孩&#xff0c;正通过抖音电商&#xff0c;书写着她自己的故事。杨儿杨的生活并不容易。5岁前&#xff…

数据库 --- mysql(01)

MYSQL 1、数据库简介 数据&#xff1a;描述事物的符号记录&#xff0c; 可以是数字、 文字、图形、图像、声音、语言等&#xff0c;数据有多种形式&#xff0c;它们都可以经过数字化后存入计算机。 数据库&#xff1a;存储数据的仓库&#xff0c;是长期存放在计算机内、有组…

武大+上交提出 BatGPT:创新性采用双向自回归架构,可预测前后token

进NLP群—>加入NLP交流群 本论文介绍了一种名为BATGPT的大规模语言模型&#xff0c;由武汉大学和上海交通大学联合开发和训练。 该模型采用双向自回归架构&#xff0c;通过创新的参数扩展方法和强化学习方法来提高模型的对齐性能&#xff0c;从而更有效地捕捉自然语言的复杂…

Seata 分布式事务的中间件Seata设计和实现方案

文章目录 分布式事务的中间件SeataSeata AT 模式-默认模式前提整体机制写隔离读隔离 Seata XA 模式前提整体机制工作机制 Seata TCC 模式Seata Saga 模式概述缺点&#xff1a; Saga的实现外传 分布式事务的中间件Seata Seata 是一款开源的分布式事务解决方案&#xff0c;致力于…

element ui组件的自定义类名样式不生效

element ui中&#xff0c;类似描述列表这种组件 会提供自定义类名属性 需要注意&#xff0c;样式不能写在<style scoped>标签中&#xff0c;会被vue自动加上data-v属性&#xff0c;导致样式失效。 必须写在<style>标签里

C++进阶—红黑树详解及map、set封装(3)

目录 1. 红黑树的概念 2. 红黑树的性质 3. 红黑树节点的定义 4. 红黑树性质分析 5. 红黑树插入节点简要分析&#xff08;新插入节点的parent为红色&#xff09; 5.1 简要分析1-变色&#xff1a; 5.2 简要分析2-变色旋转 5.3 简要分析总结 6. 红黑树插入节点详细分析 …

Linux下载安装Redis(Ubuntu系统)

相比于 Windows 系统而言&#xff0c;Redis 更适合于在 Linux 系统上使用&#xff0c;这是由 Redis 的底层机制决定的。下面介绍一下如何在 Linux 发行版 Ubuntu 系统上安装 Redis 数据库。 了解Redis版本 Redis 版本号采用国际标准惯例&#xff0c;即“主版本号.副版本号.补…

Linux分布式应用 Zabbix监控软件 安装

zabbix 是什么&#xff1f; ●zabbix 是一个基于 Web 界面的提供分布式系统监视以及网络监视功能的企业级的开源解决方案。 ●zabbix 能监视各种网络参数&#xff0c;保证服务器系统的安全运营&#xff1b;并提供灵活的通知机制以让系统管理员快速定位/解决存在的各种问题。 ●…

第七届御网杯re的wp_Ba0

re拿了一血和二血&#xff0c;感觉挺简单的&#xff08; 1、easycpp 使用IDA进行linux动调 主要异或加密&#xff0c;还原即可 1 2 3 4 flag1[0x23,0x21,0x27,0x22,0x27,0x27,0x25,0x2B,0x2D,0x26,0x23,0x23,0x22,0x26,0x27,0x2E] flag[18,19,20,22,18,17,18,19,20,22,18,17…

visual stodio 编译

一、生成文件复制一份到其他路径 选到这里&#xff0c;添加命令&#xff1a; PlatformName 平台版本 x86/x64 Configuration 配置生成目录 Debug/Release OutputPath 生成路径 Debug/Release copy /y "$(OutputPath)$(ProjectName).dll" "E:\Project\UseDll…