gpt4 book ai didi

java - 使用Java apache POI填充Excel行中的背景颜色

转载 作者:行者123 更新时间:2023-11-30 07:46:08 27 4
gpt4 key购买 nike

我正在尝试读取 Excel 工作表并使用以下代码填充行的背景颜色:

....
HSSFCellStyle cellStyle1 = workbook.createCellStyle();
cellStyle1.setFillForegroundColor(new HSSFColor.BLACK().getIndex());
cellStyle1.setFillBackgroundColor(new HSSFColor.RED().getIndex());
cellStyle1.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);

for(int i=0;i < rowCount;i++){
sheet.getRow(i).setRowStyle(cellStyle1);
}
...

当我运行代码时,仅空白单元格的颜色被填充。对于包含数据的所有单元格,颜色没有变化。有人能告诉我为什么会这样吗?

最佳答案

事实证明,设置setFillForegroundColor是为了设置单元格背景颜色。注释掉 setFillBackgroundColor 它应该可以工作。

CellStyle cellStyle1 = workbook.createCellStyle();
cellStyle1.setFillForegroundColor(IndexedColors.RED.index);
//cellStyle1.setFillBackgroundColor(IndexedColors.RED.index);
cellStyle1.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);

已编辑**

工作测试代码

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Iterator;

import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
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;


public class TestPoi {
public static void main(String[] args) throws Exception {
System.out.println("Started");
Workbook workbook = new HSSFWorkbook(new FileInputStream("input.xls"));

CellStyle cellStyle1 = workbook.createCellStyle();
cellStyle1.setFillForegroundColor(IndexedColors.RED.index);
//cellStyle1.setFillBackgroundColor(IndexedColors.RED.index);
cellStyle1.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);

Sheet sheet = workbook.getSheet("Sheet1");

Iterator<Row> rowIterator = sheet.rowIterator();
while(rowIterator.hasNext()){
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
while(cellIterator.hasNext()) {
Cell cell = cellIterator.next();
cell.setCellStyle(cellStyle1);
/*HSSFCellStyle style = (HSSFCellStyle)cell.getCellStyle();
style.setFillBackgroundColor(IndexedColors.RED.index);*/
System.out.println(cell.getStringCellValue());
}
}
workbook.write(new FileOutputStream("output.xls"));
System.out.println("Ended");
}
}

关于java - 使用Java apache POI填充Excel行中的背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33936946/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com