2017-08-08 1797 views
0

我希望有人可以帮忙。如何在XWPFTableCell上设置自定义背景颜色?

我试图使用Apache poi生成docx文件,我可以但现在我有一个问题,如何在表格列或单元格中设置背景颜色?

我试图实现这样的事情。 here

这是我到目前为止。 here

以下是我的代码。

public static void main(String [] args){ 
    XWPFDocument doc = new XWPFDocument(); 
    XWPFTable table = doc.createTable(3, 4); 
    fillHeader(table); 
    mergeCellsHorizontally(table, 0, 0, 1); 
    mergeCellsVertically(table, 2, 0, 1); 
    mergeCellsVertically(table, 3, 0, 1); 
} 

private static void fillHeader(XWPFTable table) { 
    XWPFTableRow row = table.getRow(0); 
    row.getCell(0).setText("Column 1"); 
    row.getCell(2).setText("Column 2"); 
    row.getCell(3).setText("Column 3"); 
    XWPFTableRow row1 = table.getRow(1); 
    row1.getCell(0).setText("Col 1 Row 1"); 
    row1.getCell(1).setText("Col 2 Row 1"); 
} 

private static void mergeCellsHorizontally(XWPFTable table, int row, int 
    fromCol, int toCol) { 
    for (int cellIndex = fromCol; cellIndex <= toCol; cellIndex++) { 
     XWPFTableCell cell = table.getRow(row).getCell(cellIndex); 
     if (cellIndex == fromCol) {ue 
     cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.RESTART); 
     } else { 
     cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.CONTINUE); 
     } 
    } 
} 

private static void mergeCellsVertically(XWPFTable table, int col, int 
    fromRow, int toRow) { 
    for (int rowIndex = fromRow; rowIndex <= toRow; rowIndex++) { 
     XWPFTableCell cell = table.getRow(rowIndex).getCell(col); 
     if (rowIndex == fromRow) { 
     cell.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.RESTART); 
     } else { 
     cell.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.CONTINUE); 
     } 
    } 
} 
+2

[XWPFTableCell.setColor](https://poi.apache.org/apidocs/org/apache/poi/xwpf/usermodel/XWPFTableCell.html#setColor%28java.lang.String%29)呢?你有没有尝试过? –

+0

现在好了。我最初认为这种方法是用来改变字体颜色的。谢谢。 – blitzen12

回答

0

的小区中设置背景颜色,做象下面这样:

cell.getCTTc().addNewTcPr().addNewShd().setFill("cccccc"); 

颜色应该使用十六进制像cccccc