java - POI 仅为前 50 行添加单元格背景

标签 java apache-poi

我之前生成了 .xls(也由 Apache POI 生成),再次打开并按单元格值更改背景颜色。问题是,并非所有单元格的背景都发生了变化,而仅在前大约 50 行中发生了变化,其他仍保留白色背景。函数 mark() 在一个 for 循环中,我尝试转储值、行号,最后尝试一次又一次地迭代 xls 分配颜色,但没有任何效果...

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Font;

public class Xls {

   private FileOutputStream fileOut;
   private Sheet xlsSheet;
   private HSSFWorkbook xlsWorkbook;
   private CellStyle cellStyle;

   public Xls(String path) {
    try {
        fileOut = new FileOutputStream(path);
        this.xlsWorkbook = new HSSFWorkbook();
        this.xlsSheet = xlsWorkbook.createSheet("test");

        cellStyle = this.xlsWorkbook.createCellStyle();

        Row row1 = xlsSheet.createRow((int) 0);

        this.xlsSheet.autoSizeColumn(0, true);
        this.xlsSheet.autoSizeColumn(1, true);
        this.xlsSheet.autoSizeColumn(2, true);
        this.xlsSheet.autoSizeColumn(3, true);

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    public void mark(int rowNumber, String status) {
        short color = Constants.getColor(status);

        CellStyle style = this.xlsWorkbook.createCellStyle();

        style.setFillForegroundColor(color);
        style.setFillPattern(CellStyle.SOLID_FOREGROUND);
        //TODO!!! Why filling color only in first 50 rows?!
//            System.out.println("Changing row " + sameRows.get(rowNumber) + " status is:'" + status + "' color:" + color);
            Row row = xlsSheet.getRow(sameRows.get(rowNumber));
            Cell statusCell = null;
            if (!isCellEmpty(row.getCell(3))) {
                statusCell = row.getCell(3);
            } else {
                statusCell = row.createCell(3);
            }

            statusCell.setCellValue(status);
            statusCell.setCellStyle(style);
        }
    }

}

你知道哪里可能出错吗? 注意:setCellValue() 正在运行 - 所有字段都有正确的值。

最佳答案

不应为每个单元格重新创建 CellStyles,它们是 Excel 文件中的有限资源(限制由 Excel 本身施加),因此只需创建一次样式对象,然后将其重新用于所有应该使用的单元格风格相同。

关于java - POI 仅为前 50 行添加单元格背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36178466/

相关文章:

java - 使用 JavaCompiler 包在另一个 Java 类中获取编译 Java 源文件的结果

java - 大规模文档共现分析

java - Excel 单元格数据在使用 Apache POI 时发生更改

用于将任何文件的内容转换为文本文件的 Java 实用程序。

Java 将字符串作为 URL 保存到 Excel 文件

java - JBoss EAP 6.2GA Managed Domain Exploded-Deployment

Java内存游戏

选择性目录的 Java 编译错误

ms-word - 无法用 MS Word 文件中的 Apache POI 替换阿拉伯字符

java - 我正在使用 Apache POI 将 PPTX 幻灯片转换为图像,但生成的图像的大小非常巨大,超过 1.5 mb