Poi自定颜色操作单元格

话不多说,直接撸代码

package com.example.util;


import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.junit.jupiter.api.Test;

import java.io.File;
import java.io.IOException;

/**
 * @program: boot
 * @description
 * @author: 
 * @create: 2020-08-23 15:43
 **/
public class ExeclUtilTest {

    /**
     * 设置豆绿色填充色
     *
     * @throws IOException
     */
    @Test
    public void exportExcel() throws IOException {
        // 创建HSSFWorkbook对象
        HSSFWorkbook hssfWorkbook = new HSSFWorkbook();
        // 定义 loginusers 的sheet页
        HSSFSheet sheet = hssfWorkbook.createSheet("loginusers");
        // 创建第一行对象 HSSFRow
        HSSFRow row = sheet.createRow(0);

        HSSFCell cell = row.createCell(0);
        cell.setCellValue("test1011");

        // 豆绿色的rgb为(199,237,204)
        // 创建HSSFPalette对象
        HSSFPalette palette = hssfWorkbook.getCustomPalette();
        // 将绿色的rgb覆写为豆绿的rgb(199,237,204),这样绿色的索引17就代表了豆绿色的
        // HSSFColor.GREEN.index获取绿色索引已过时,改用此IndexedColors.GREEN.getIndex()获取索引
        palette.setColorAtIndex(IndexedColors.GREEN.getIndex(), (byte) 199, (byte) 237, (byte) 204);

        System.out.println(IndexedColors.GREEN.getIndex());
        // 创建 HSSFCellStyle 对象
        HSSFCellStyle cellStyle = hssfWorkbook.createCellStyle();
        // 设置单元格样式为豆绿色
        cellStyle.setFillForegroundColor(IndexedColors.GREEN.getIndex());
        // 设置样式为填充,很重要,没有该设置,excel单元格将不会渲染填充
        cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        cell.setCellStyle(cellStyle);

        // 第二列设值
        HSSFCell cell1 = row.createCell(1);
        cell1.setCellValue("test2");

        // 第三列设值
        HSSFCell cell2 = row.createCell(2);
        cell2.setCellValue("test3");
        
        // 第四列设值
        HSSFCell cell3 = row.createCell(3);
        cell3.setCellValue("test4");
        // 通过类加载器设置导出路径
        String path = getClass().getClassLoader().getResource("").getPath();
        System.out.println(path);
        File file = new File(path + File.separator + "color.xls");
        // hssfWorkbook 写入到文件
        hssfWorkbook.write(file);
        System.out.println("success ");
    }

}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值