首页 > 解决方案 > 如何从 docx 中创建的表中删除空白列?

问题描述

我写了一本外语发音指南。它包含有关列表中每个单词的信息。我想使用 docx 在原始单词上方显示发音指南,在单词下方显示词性。

期望的结果如下所示:

pronunciation_1 | pronunciation_2 | pronunciation_3
---------------------------------------------------
word_1          | word_2          | word_3
---------------------------------------------------
part_of_speech_1 | part_of_speech_2|part_of_speech_3

这是我尝试使其工作的代码示例。

from docx import Document
from docx.shared import Inches
document = Document()
table = document.add_table(rows=3,cols=1)
word_1 = ['This', "th is", 'pronoun']
word_2 = ['is', ' iz', 'verb']
word_3 = ['an', 'uh n', 'indefinite article']
word_4 = ['apple.','ap-uh l', 'noun']
my_word_collection = [word_1,word_2,word_3,word_4]
for word in my_word_collection:
    my_word = word[0]
    pronounciation = word[1]
    part_of_speech = word[2]
    column_cells = table.add_column(Inches(.25)).cells
    column_cells[0].text = pronounciation
    column_cells[1].text = my_word
    column_cells[2].text = part_of_speech
document.save('my_word_demo.docx')

结果如下: 我的代码如何在 MS Word 2010 中呈现文本的屏幕截图

我的具体问题是:

我怎样才能摆脱空白的第一列?

我不知道为什么它一直出现,但它确实......提前谢谢你帮助我!

标签: pythonpython-3.xdocxpython-docx

解决方案


第一列是从初始表创建开始的,它是空白的,因为您在编写每个项目之前都创建了一个新列。所以你需要这样的东西来“用完”第一个单词的第一列,然后只创建新列:

table = document.add_table(rows=3, cols=1)
for idx, word in enumerate(words):
    column = table.columns[0] if idx == 0 else table.add_column(..)
    cells = column.cells
    ...

推荐阅读