如何在Apache POI中为XWPFTable设置黑色主题?
Achieving a Black Theme for Your XWPFTable
Absolutely, you can replicate Microsoft Word's black theme effect for your Apache POI XWPFTable. This involves setting a black cell background, white text for readability, and white borders to maintain table structure. Here's how to modify your existing code:
Step-by-Step Implementation
First, here's your original code updated with the black theme styling:
table = ForensicExpertWitnessReport_doc.insertNewTbl(cursor); // Create first row of table // File Name XWPFTableRow tableRowOne = table.getRow(0); tableRowOne.getCell(0).setText("File Name"); tableRowOne.addNewTableCell(); if (filename != null) { tableRowOne.getCell(1).setText(filename); } // --- Start of Black Theme Styling --- // 1. Set table borders to white for visibility against black background CTTblPr tblPr = table.getCTTbl().getTblPr(); CTTblBorders tblBorders = tblPr.isSetTblBorders() ? tblPr.getTblBorders() : tblPr.addNewTblBorders(); // Define white border properties (1pt thickness) CTBorder border = CTBorder.Factory.newInstance(); border.setColor("FFFFFF"); // White hex code border.setSz(new BigInteger("8")); // 1pt = 8 units in Apache POI border.setVal(STBorder.SINGLE); // Apply border to all table sides and internal lines tblBorders.setTop(border); tblBorders.setBottom(border); tblBorders.setLeft(border); tblBorders.setRight(border); tblBorders.setInsideH(border); tblBorders.setInsideV(border); // 2. Style each cell with black background and white text for (XWPFTableRow row : table.getRows()) { for (XWPFTableCell cell : row.getTableCells()) { // Set cell background to solid black CTTc cttc = cell.getCTTc(); CTTcPr ctTcPr = cttc.isSetTcPr() ? cttc.getTcPr() : cttc.addNewTcPr(); CTShd ctShd = ctTcPr.isSetShd() ? ctTcPr.getShd() : ctTcPr.addNewShd(); ctShd.setFill("000000"); // Black hex code ctShd.setVal(STShd.CLEAR); // Use solid fill // Set all text in the cell to white for (XWPFParagraph para : cell.getParagraphs()) { for (XWPFRun run : para.getRuns()) { run.setColor("FFFFFF"); // White hex code // Optional: Make text bold for better contrast // run.setBold(true); } } } } // --- End of Black Theme Styling ---
Key Details Explained
- White Borders: We set the table borders to white so they're visible against the black background. The size
8corresponds to 1 point (the standard border thickness in Word). - Black Cell Background: Using
CTShd, we apply a solid black fill to each cell. ThesetVal(STShd.CLEAR)ensures the fill is solid rather than patterned. - White Text: Every text run in each cell is set to white to ensure readability against the dark background. You can optionally enable bold text for even better contrast.
Important Note
If you add additional rows or cells to the table later, you'll need to apply the same styling to those new elements. You could wrap the cell styling logic in a helper method to reuse it easily.
内容的提问来源于stack exchange,提问作者Polarbearz




