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

2023-11-01


需要的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博客

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

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

随机推荐

  • 清风数学建模学习笔记——熵权法(客观赋权法)

    熵权法 熵权法是一种客观赋权方法 客观 数据本身就可以告诉我们权重 依据的原理 指标的变异程度越小 所反映的信息量也越少 其对应的权值也应该越低 本文借鉴了数学建模清风老师的课件与思路 如果大家发现文章中有不正确的地方 欢迎大家在评论区留言
  • Vue.js用cdn方式引入

    Vue js用cdn方式引入 前言 注意本次用cdn形式引入js学习 有node js的玩家可以用node js CDN下载地址 https vuejs org js vue min js以及Node js Vue系列 windows下np
  • 解决asterisk sip错误提示Not Acceptable Here(488)或Not Found(404)

    安装好asterisk后对接到VOS3000使用 可发现VOS死活送不通asterisk 于是回头检查asterisk系统是否安装正确以及是否正常工作 经过反复检查 都没有发现问题 可VOS上面话单显示 开始一直显示488错误 于是我看了下
  • policy gradient详解(附代码)

    1 引言 policy gradient是强化学习中一种基于概率策略的方法 智能体通过与环境的交互获得特定时刻的状态信息 并直接给出下一步要采取各种动作的概率 然后根据该状态动作的策略分布采取下一步的行动 所以每种动作都有可能被选中 只是选
  • 计算 属性

    一 定义 计算属性就是当其依赖属性的值发生变化时 这个属性的值会自动更新 预支相关的DOM部分也会同步自动更新 有缓存 二 用法 1 基础用法 computed getN return this n 1 2 传递参数 返回一个函数 h1 t
  • mmdetection源码阅读

    阅读从tools train py开始 功能模块 Register类 位置 utils registry py 用于注册起到相同作用的 例如coco voc数据类 模型类 数据处理流程类 类别 具体功能是这样的 Register的 init
  • 很不起眼的6个bug,90%的程序员就算写了10年代码也肯定都踩过!

    文章来源 https juejin cn post 7120570066856312839 前言 作为Java程序员的你 不知道有没有踩过一些基础知识的坑 有时候 某个bug查了半天 最后发现竟然是一个低级错误 有时候 某些代码 这一批数据
  • 由jar包冲突导致的logback日志不输出

    文章目录 一 前言 1 resource下面有logback配置但没有生成日志 2 去掉Log4j依赖引用 3 java是如何加载logback 3 1 回顾下我们获取日志对象是如何获取的 一 前言 最近升级一个老项目 发面日志没有按照预期
  • Hydra的基本使用

    R 根据上一次进度继续破解 S 使用SSL协议连接 s 指定端口 l 指定用户名 L 指定用户名字典 文件 p 指定密码破解 P 指定密码字典 文件 e 空密码探测和指定用户密码探测 ns C 用户名可以用 分割 username pass
  • CentOS-Linux安装 XS-Tools (XenServer)

    1 在Xencenter里光驱换成xs tools iso 2 登陆SSH root ns0 cd mnt root ns0 mnt ls root ns0 mnt mkdir xs tools root ns0 mnt mount dev
  • 在解决方案中所使用 NuGet 管理软件包依赖

    使用程序包恢复功能可以在提交源代码时 不需要将代码库提交到源代码管理中 大幅减少项目的尺寸 所有NuGet程序包都存储在解决方案的Packages文件夹中 要启用程序包恢复功能 可右键单击解决方案 注意 不是右键单击项目文件 并选择 Ena
  • C++的const成员函数

    C 的const成员函数 const成员函数是什么 实例 总结 const成员函数是什么 通常我们看到的const成员函数格式类似于 int QueryBalance int iBalanceVal const 简单的说 const成员函数
  • C++学习(三四六)cygwin 交叉编译Android gdal

    官方说gdal的android版本是仍在做的一项工作 BuildingForAndroid GDALhttps trac osgeo org gdal wiki BuildingForAndroid cygwin android ndk r
  • 快速幂计算x的n次幂,递归版本、迭代版本、python实现

    递归 分治思想 二分 def myPow self x float n int gt float def quick pow x n if n 1 return x half quick pow x n 2 y half half if n
  • Android文件存储目录结构

    应用程序在运行的过程中如果需要向手机上保存数据 一般是把数据保存在SDcard中的 大部分应用是直接在SDCard的根目录下创建一个文件夹 然后把数据保存在该文件夹中 这样当该应用被卸载后 这些数据还保留在SDCard中 留下了垃圾数据 并
  • 华为OD机试 Python【最小传输时延Ⅱ】

    题目 题目描述 想象一个M N的大网格 每个格子上都有一个数字 这个数字就是这个格子转发数据的延迟时间 每个格子可以向其周围的8个方向 上 下 左 右以及四个角落 发送数据 现在 有技巧 如果连续两个格子的延迟时间相同 那么我们只算一个时间
  • SQL SERVER专题实验3 简单查询

    第1关 基本知识 第1题 A 第2题 ABC 第3题 AB 第4题 AB 第5题 ABCD 第6题 ABCD 第7题 AC 第2关 按指定列 全部列和计算表达式的查询 本关任务 用 SELECT 语句检索数据表中指定字段的数据 按要求输出目
  • 公交路线推荐

    项目从0 1出 请写出公交车路线推荐策略 逻辑框架 心法 1 产品目标 用户以最低的代价 成本完成想要做的事情 2 需求理解 给出区分不同用户群 场景的规则 定义衡量标准 将其数字化 通常是准确率和召回率 3 提出解决方案 给出针对每个用户
  • 逻辑运算符

    逻辑运算符 逻辑运算符概述 短路逻辑运算符 之间的区别 逻辑运算符概述 可以把多个条件的布尔结果放在一起运算 最终返回一个布尔结果 double length 11 5 double width 6 95 需求 长度大于等于10cm 宽度大
  • Java POI excel单元格背景色(填充)、字体颜色(对齐)、边框(颜色)、行高、列宽设置

    文章目录 1 Excel Cell单元格背景色 颜色名称对照关系 2 Excel Cell单元格背景填充样式 颜色填充对照关系 3 Excel Cell字体样式设置 对照图 4 Excel 行高 列宽设置 5 Excel单元格边框设置 边框