使用Python Docx生成大表格时列宽度设置失效问题求助
问题根源
这是Word表格默认开启的自动调整功能导致的列宽被覆盖问题:python-docx默认生成的表格允许Word根据内容自动调整列宽,小表格内容总长度未触发自动调整阈值时手动设置的单元格宽度可以生效,当表格行数达到上千行后,Word的自动适配逻辑会覆盖你设置的宽度参数,导致列宽不符合预期。
修复步骤
1. 彻底关闭表格自动调整功能
创建表格后立即添加两行配置,完全禁用Word的自动列宽调整逻辑:
table = doc.add_table(rows= row_ttl, cols= col_ttl) table.style='Light Grid Accent 1' # 新增以下两行,彻底关闭自动调整 table.autofit = False table.allow_autofit = False
2. 优化宽度设置方式(可选,提升大表格生成效率)
不用逐行逐单元格设置宽度,直接按列设置宽度即可,同时避免重复读取配置:
# 提前读取宽度、对齐配置,避免循环内重复读取 widths = set_width_dic[file] align_map = {item[0]: item[1] for item in set_alignment_dic[file]} # 直接按列设置宽度,效率更高 for col_idx, col in enumerate(table.columns): col.width = widths[col_idx]
3. 优化内容填充逻辑
将对齐配置提前转为字典,避免循环内反复遍历对齐列表,提升大表格生成速度:
for r in range(len(list_of_lists)): for c, cell in enumerate(table.rows[r].cells): cell.vertical_alignment = WD_ALIGN_VERTICAL.BOTTOM par = cell.add_paragraph(str(list_of_lists[r][c])) # 直接从提前生成的对齐字典取配置,无需循环判断 par.alignment = align_map[c]
修复后完整测试代码
from docx import Document from docx.shared import Cm, Pt, Inches import docx from docx.enum.text import WD_ALIGN_PARAGRAPH from docx.enum.table import WD_ALIGN_VERTICAL year = '2019' # 这里自行替换你的file和path参数值 file = 'PUR'+year +'_subtotals_indexed_by_chemical.txt' path = './' set_width_dic = { 'PUR'+year +'_subtotals_indexed_by_site.txt':(Inches(3.50), Inches(1.25), Inches(1.25)), 'PUR'+year +'_subtotals_indexed_by_chemical.txt':(Inches(3.50), Inches(1.25), Inches(1.25))} set_alignment_dic = { 'PUR'+year +'_subtotals_indexed_by_site.txt':[[0,WD_ALIGN_PARAGRAPH.LEFT, 'Commodity or site'],[1,WD_ALIGN_PARAGRAPH.RIGHT, 'Pounds Applied'],[2,WD_ALIGN_PARAGRAPH.RIGHT, 'Agricultural Applications']], 'PUR'+year +'_subtotals_indexed_by_chemical.txt':[[0,WD_ALIGN_PARAGRAPH.LEFT, 'Chemical'],[1,WD_ALIGN_PARAGRAPH.RIGHT, 'Pounds Applied'],[2,WD_ALIGN_PARAGRAPH.RIGHT, 'Agricultural Applications']]} #the data list_of_lists = ['Chemical', 'Pounds Applied', 'Agricultural Applications'],['ABAMECTIN', '51,276.54', '69,659'],['ABAMECTIN, OTHER RELATED', '0.03', 'N/A'], ['S-ABSCISIC ACID', '1,856.38', '230'],['ACEPHATE', '158,054.76', '11,082'],['SULFUR','49,038,554.00','170,396'],['BACILLUS SPHAERICUS 2362, SEROTYPE H5A5B, STRAIN ABTS 1743 FERMENTATION SOLIDS, SPORES AND INSECTICIDAL TOXINS','11,726.29','N/A'] doc = docx.Document() col_ttl = 3 row_ttl = len(list_of_lists) # 直接取数据长度,避免手动填写出错 table = doc.add_table(rows= row_ttl, cols= col_ttl) table.style='Light Grid Accent 1' # 核心修复:彻底关闭自动调整 table.autofit = False table.allow_autofit = False # 提前读取配置 widths = set_width_dic[file] align_map = {item[0]: item[1] for item in set_alignment_dic[file]} # 统一设置列宽 for col_idx, col in enumerate(table.columns): col.width = widths[col_idx] # 填充内容 for r in range(len(list_of_lists)): for c, cell in enumerate(table.rows[r].cells): cell.vertical_alignment = WD_ALIGN_VERTICAL.BOTTOM par = cell.add_paragraph(str(list_of_lists[r][c])) par.alignment = align_map[c] doc.save(path+'try.docx')
内容的提问来源于stack exchange,提问作者ksteinmann
相关产品推荐
相关产品推荐

