Python_Learner
Python_Learner

Reputation: 1657

How remove blank column from table created in docx?

I have written a pronunciation guide for a foriegn language. It has information about each word in a list. I want to use docx to show the pronunciation guide above the original words and the part of speech below the words.

The desired result looks like this:

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

Here's a code example of my attempt to get this to work.

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')

Here's what the results look like: Screenshot of how my code renders the text in MS Word 2010

My specific question is:

How can I get rid of that blank first column?

I don't know why it keeps showing up, but it does...thank you in advance for helping me!

Upvotes: 1

Views: 1295

Answers (1)

scanny
scanny

Reputation: 28991

The first column is there from the initial table creation and it's blank because you create a new column before writing each item. So you need something like this to "use up" the first column for the first word and only create new columns thereafter:

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
    ...

Upvotes: 1

Related Questions