Java中用Apache POI的XWPFParagraph/XWPFRun实现docx表格行对齐
Hey there! I’ve dealt with this exact alignment headache when building docx tables with Apache POI—nothing looks messier than one cell’s wrapped text sitting out of sync with the rest of the row. Let’s walk through how to get everything lined up perfectly:
1. Enforce Uniform Vertical Alignment Across the Row
The first fix is making sure every cell in your second row uses the same vertical alignment. When one cell wraps text and others don’t, their default vertical positions can drift—setting a consistent alignment (like center) will lock them all to the same baseline.
// Grab your second row (remember, POI uses 0-based indexing) XWPFTableRow targetRow = yourTable.getRow(1); // Loop through each cell in the row to set vertical alignment for (XWPFTableCell cell : targetRow.getTableCells()) { // Use CENTER, TOP, or BOTTOM depending on your desired layout cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER); }
2. Standardize Paragraph Settings for Consistency
Even with vertical alignment set, inconsistent paragraph spacing can throw things off. Let’s make sure every cell’s paragraph has the same line spacing and horizontal alignment:
for (XWPFTableCell cell : targetRow.getTableCells()) { // Get the first (and likely only) paragraph in the cell XWPFParagraph para = cell.getParagraphs().get(0); // Set horizontal alignment (LEFT is standard for table content) para.setAlignment(ParagraphAlignment.LEFT); // Set consistent line spacing to avoid uneven row height CTPPr paragraphProps = para.getCTP().getPPr(); if (paragraphProps == null) { paragraphProps = para.getCTP().addNewPPr(); } CTSpacing spacing = paragraphProps.getSpacing(); if (spacing == null) { spacing = paragraphProps.addNewSpacing(); } // Use 240 twips for 1.5x line spacing (1440 twips = 1 inch) spacing.setLine(BigInteger.valueOf(240)); spacing.setLineRule(STLineSpacingRule.AUTO); }
3. Optional: Let the Row Auto-Adjust Its Height
If you want the row to automatically expand to fit the tallest cell (the one with wrapped text), enable auto-height for the row:
CTTrPr rowProps = targetRow.getCtRow().addNewTrPr(); CTHeight rowHeight = rowProps.addNewTrHeight(); rowHeight.setVal(BigInteger.valueOf(0)); // 0 = auto-height rowHeight.setHRule(STHeightRule.AUTO);
Quick Recap
- Vertical alignment locks all cell content to the same vertical position, regardless of line count.
- Standardized paragraph spacing ensures no unexpected gaps or cramped text.
- Auto-row height lets the row grow to fit the longest content without cutting it off.
This should make your second row look clean and aligned, even when one cell needs to wrap its text!
内容的提问来源于stack exchange,提问作者Rajen Ranpara




