我正在使用apache poi和XLSX文件.我使用xssf类动态创建电子表格.我想在for循环中设置单元格的样式,但它似乎不起作用......这是我的代码:
for(int i=1;i<=gc.getActualMaximum(GregorianCalendar.DAY_OF_MONTH);i++,gc.add(GregorianCalendar.DATE, 1),righe++){
Row r = foglio.createRow(righe);
if(getDayOfWeek(gc)== 6 || getDayOfWeek(gc) == 7){
XSSFCellStyle cs1 = wb.createCellStyle();
cs1.setFillBackgroundColor(IndexedColors.YELLOW.getIndex());
cs1.setFillPattern(CellStyle.SOLID_FOREGROUND);
XSSFFont f = wb.createFont();
f.setBold(true);
f.setColor(IndexedColors.RED.getIndex());
cs1.setFont(f);
Cell c1 = r.createCell(0);
c1.setCellValue(cost.getGiorni().get(getDayOfWeek(gc)-1).getNomeGiorno());
c1.setCellStyle(cs1);
Cell c2 = r.createCell(1);
c2.setCellValue(i);
c2.setCellStyle(cs1);
}
r.createCell(0).setCellValue(cost.getGiorni().get(getDayOfWeek(gc)-1).getNomeGiorno());
r.createCell(1).setCellValue(i);
Run Code Online (Sandbox Code Playgroud)
...这只是代码的一部分......我无法理解为什么不工作.似乎像cellstyle被忽略或者被淹没....
任何线索?
您可以使用以下方法,这可能会解决您的问题.
public static void setCellColorAndFontColor(XSSFCell cell, IndexedColors FGcolor, IndexedColors FontColor ){
XSSFWorkbook wb = cell.getRow().getSheet().getWorkbook();
CellStyle style = wb.createCellStyle();
XSSFFont font = wb.createFont();
font.setBold(true);
font.setColor(FontColor.getIndex());
style.setFont(font);
style.setFillForegroundColor(FGcolor.getIndex());
style.setFillPattern(CellStyle.SOLID_FOREGROUND);
cell.setCellStyle(style);
}
Run Code Online (Sandbox Code Playgroud)
当你调用这种方法时,应该是这样的
setCellColorAndFontColor(cell, IndexedColors.BLACK, IndexedColors.WHITE);
Run Code Online (Sandbox Code Playgroud)
将在工作表中创建带有黑色单元格背景颜色的粗体和白色字体文本颜色.
CellStyles 是针对每个工作簿的,Excel 对文件允许的数字有一个硬性限制,因此您需要确保在循环外创建单元格样式。
您的代码将如下所示:
XSSFCellStyle cs1 = wb.createCellStyle();
cs1.setFillBackgroundColor(IndexedColors.YELLOW.getIndex());
cs1.setFillPattern(CellStyle.SOLID_FOREGROUND);
XSSFFont f = wb.createFont();
f.setBold(true);
f.setColor(IndexedColors.RED.getIndex());
cs1.setFont(f);
for(int i=1;i<=gc.getActualMaximum(GregorianCalendar.DAY_OF_MONTH) i++,gc.add(GregorianCalendar.DATE, 1),righe++){
Row r = foglio.createRow(righe);
if(getDayOfWeek(gc)== 6 || getDayOfWeek(gc) == 7){
Cell c1 = r.createCell(0);
c1.setCellValue(cost.getGiorni().get(getDayOfWeek(gc)-1).getNomeGiorno());
c1.setCellStyle(cs1);
Cell c2 = r.createCell(1);
c2.setCellValue(i);
c2.setCellStyle(cs1);
}
}
Run Code Online (Sandbox Code Playgroud)
如果您的样式看起来不像您预期的那样有问题,最好的选择是在 Excel 中根据需要设置单元格的样式,保存文件,将其读入 POI,然后查看 Excel 编写的单元格样式。有时,Excel 会做一些奇怪的事情,需要一些时间来适应,所以请检查它的作用来确定您需要做什么!
| 归档时间: |
|
| 查看次数: |
21461 次 |
| 最近记录: |