首页 > 解决方案 > 使用 Python Docx 设置表格宽度时遇到问题

问题描述

我每年都必须创建大量的表格 pdf,所以我试图用 Docx 编写一个脚本来在 Word 中创建表格,每列都有自己的设置宽度和左对齐或右对齐。现在我正在处理两张表 - 一张有 262 行,另一张有 1036 行。该代码适用于 262 行的表,但不会为 1036 行的表正确设置列宽。由于两个表的代码相同,我认为这是数据本身的问题,或者可能是表的大小?我尝试在没有任何数据的情况下创建第二个较大的表,并且宽度是正确的。然后,我尝试使用 1036 行中的 7 行的子集创建下表,包括字符数最多的行,以防列不换行而是强制更改列宽。它运行良好 - 宽度是正确的。我在 1036 行的完整数据集上使用完全相同的代码,并且宽度发生了变化。有任何想法吗?

下面是仅 7 行数据的代码。它工作正常 - 第一列是 3.5 英寸,第二和第三列是 1.25 英寸。

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'

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() # Create an instance of a word document
col_ttl = 3 # add enough columns as headings in the first list in list_of_lists
row_ttl =7# add rows to equal total number lists in list_of_lists
# Creating a table object
table = doc.add_table(rows= row_ttl, cols= col_ttl)
table.style='Light Grid Accent 1'
for r in range(len(list_of_lists)):
    row=table.rows[r]
    widths = set_width_dic[file] #Ex of widths = (Inches(3.50), Inches(1.25), Inches(1.25))
    for c, cell in enumerate(table.rows[r].cells):#c is an index, cell is the empty cell of the table, 
        table.cell(r,c).vertical_alignment = WD_ALIGN_VERTICAL.BOTTOM
        table.cell(r,c).width = widths[c]
        par = cell.add_paragraph(str(list_of_lists[r][c]))
        for l in set_alignment_dic[file]:
            if l[0] == c:
                par.alignment = l[1] 
doc.save(path+'try.docx')

当我尝试对整个 list_of_lists(1036 个列表的列表)执行完全相同的代码时,宽度不正确:第 1 列 = 4.23",第 2 列 = 1.04",第 3 列 = 0.89"

我在我的 cmd 框中打印了完整的 1036 行 list_of_lists,然后将其粘贴到一个文本文件中,我认为我可以将它包含在此处。但是,当我尝试运行完整列表时,它不会粘贴回 cmd 框中 - 它给出了 EOL 错误,并且只显示了 list_of_lists 中的前 65 个列表。DocX 能够制作完整的表格,只是不会设置正确的宽度。我很困惑。我浏览了我能找到的每个 StackExchange python Docx 表格宽度帖子,以及许多其他谷歌搜索网站。任何想法都非常感谢。

标签: pythonwidthpython-docxword-table

解决方案


才发现问题。我需要添加 autofit = False。现在代码也适用于更长的表

        table.autofit = False 
        table.allow_autofit = False

推荐阅读