使用python-docx设置表格单元格右对齐时WD_TAB_ALIGNMENT不生效如何处理
问题原因
你用错了参数,WD_TAB_ALIGNMENT是制表位专属的对齐参数,不适用单元格文本对齐场景。单元格内文本对齐需要调整段落的对齐属性,对应参数为WD_PARAGRAPH_ALIGNMENT。
调整步骤
- 先导入所需的对齐常量
- 给需要右对齐的单元格段落设置
alignment属性为WD_PARAGRAPH_ALIGNMENT.RIGHT即可
修改后完整代码
# 新增导入对齐常量 from docx.enum.text import WD_PARAGRAPH_ALIGNMENT from docx.shared import Inches # 原有列宽设置不变 table.columns[0].width = Inches(14.0) table.columns[1].width = Inches(2.0) table.columns[2].width = Inches(2.0) table.columns[3].width = Inches(3.0) hdr_cells = table.rows[0].cells hdr_cells[0].paragraphs[0].add_run("article") # 表头后三列设置右对齐 hdr_cells[1].paragraphs[0].add_run("count") hdr_cells[1].paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.RIGHT hdr_cells[2].paragraphs[0].add_run("price") hdr_cells[2].paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.RIGHT hdr_cells[3].paragraphs[0].add_run("total") hdr_cells[3].paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.RIGHT for i in range (0, len(records)): row_cells = table.add_row().cells row_cells[0].paragraphs[0].add_run(records[i][0]) # 数量、价格、总价列设置右对齐 row_cells[1].paragraphs[0].add_run(records[i][1]) row_cells[1].paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.RIGHT row_cells[2].paragraphs[0].add_run(records[i][2]) row_cells[2].paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.RIGHT row_cells[3].paragraphs[0].add_run(records[i][3]) row_cells[3].paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.RIGHT
可选优化(减少重复代码)
可以封装一个辅助函数简化对齐设置:
def set_cell_right_align(cell, content): cell.paragraphs[0].add_run(content) cell.paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.RIGHT # 调用示例 set_cell_right_align(hdr_cells[1], "count") set_cell_right_align(row_cells[1], records[i][1])
内容的提问来源于stack exchange,提问作者Hans Dampf
相关产品推荐
相关产品推荐

