2017-08-08 82 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