POI Excel - 颜色单元格

POI Excel - 颜色单元格 首页 / POI入门教程 / POI Excel - 颜色单元格

Apache POI允许无涯教程同时在背景(background)和前景(foreground)中设置单个单元格的颜色。为此,它提供了有助于设置单元格颜色的方法。

在下面的示例中,将创建两个单元格并将颜色分别填充到背景和前景,参见示例。

Excel单元格颜色示例

package poiexample;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ColorExample {
	public static void main(String[] args) throws FileNotFoundException, IOException {
		try (OutputStream fileOut = new FileOutputStream("Learnfk.xls")) {
		    Workbook wb = new XSSFWorkbook();
		    Sheet sheet = wb.createSheet("Sheet");
		    Row row = sheet.createRow(1);
		    CellStyle style = wb.createCellStyle();
		   //设置背景颜色
		    style.setFillBackgroundColor(IndexedColors.GREEN.getIndex());
		    style.setFillPattern(FillPatternType.BIG_SPOTS);
		    Cell cell = row.createCell(1);
		    cell.setCellValue("Javatpoint");
		    cell.setCellStyle(style);
		   //设置前景色
		    style = wb.createCellStyle();
		    style.setFillForegroundColor(IndexedColors.BLUE.getIndex());
		    style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
		    cell = row.createCell(2);
		    cell.setCellValue("A Technical Portal");
		    cell.setCellStyle(style);
                    wb.write(fileOut);
                 }catch(Exception e) {
		    	System.out.println(e.getMessage());
		}
	}
}

输出:

Apache POI Excel Cell Color

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

如何设计一个秒杀系统 -〔许令波〕

10x程序员工作法 -〔郑晔〕

DDD实战课 -〔欧创新〕

MongoDB高手课 -〔唐建法(TJ)〕

Linux内核技术实战课 -〔邵亚方〕

技术管理案例课 -〔许健〕

Vue 3 企业级项目实战课 -〔杨文坚〕

AI大模型系统实战 -〔Tyler〕

手把手带你写一个 MiniTomcat -〔郭屹〕

好记忆不如烂笔头。留下您的足迹吧 :)