Java POI excel cell background color (fill), font color (alignment), border (color), row height, column width settings


Required Maven environment configuration

    <!-- 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>

Some problems that need attention are written in the code by means of comments. When reading the code, you need to pay attention to the comments

1. Excel Cell cell background color + color name comparison relationship

    /**
     * 设置单元格背景颜色
     * <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 cell background fill style + color fill control relationship

    /**
     * 设置背景颜色填充效果
     * <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 font style setting + comparison chart

    /**
     * 设置单元格字体样式
     */
    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 row height and column width settings

    /**
     * 行高列宽设置
     */
    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 cell border setting + border type picture comparison

    /**
     * 设置多有边框样式 + 颜色
     */
    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();
    }

Border style comparison table, the BorderStyle enumeration object is in the brackets

insert image description here

Attachment 1: some questions

1. Regarding the calculation method of column width using pound * 20

image.png

2. About the calculation method of line height using pound*256+185

image.png

3. Regarding the incorrect final row number of sheet.getLastRowNum()

image.png
If there are blank rows (the entire row is empty) in the entire Excel, and there are other data under several blank rows at that time, the final row number obtained at this time is wrong, especially when there are merged cells, this kind of problem is most likely to occur.
image.png
Obviously, 10, 11, 13, and 14 are all empty lines, and the lastNum at this time is incorrect, so pay special attention to this situation.

The most direct way to avoid this situation is to know in advance how many rows of data exist, and first generate all rows with sheet.createRow(0).


The same happens with blank cells. If the cell does not exist or has no style, the column number of the last cell obtained is also incorrect.

4. In IDEA, press and hold the shortcut key (Shift) + hover the mouse to the corresponding word to view the color

insert image description here
insert image description here

Attachment 2: Reference Links

Conversion of various units such as pixels, pounds, points, and
twips Gu's Blog-CSDN Blog POI4 Color
Name, Color Chinese Name, Color
Correspondence
Use POI to set the column width of Excel_sheet.setcolumnwidth_duqian42707's blog-CSDN blog
Java POI set the width and height of Excel cells_java poi set the cell width_aosica's blog-CSDN blog

Guess you like

Origin blog.csdn.net/dongzi_yu/article/details/131577857