我之前生成了 .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/