Skip to content Skip to sidebar Skip to footer

Write Tables From Word (.docx) To Excel (.xlsx) Using Xlsxwriter

I am trying to parse a word (.docx) for tables, then copy these tables over to excel using xlsxwriter. This is my code: from docx.api import Document import xlsxwriter document =

Solution 1:

I would go using pandas package, instead of xlsxwriter, as follows:

from docx.apiimportDocumentimport pandas as pd

document = Document("D:/tmp/test.docx")
tables = document.tables
df = pd.DataFrame()

for table indocument.tables:
    for row in table.rows:
        text = [cell.textfor cell in row.cells]
        df = df.append([text], ignore_index=True)

df.columns = ["Column1", "Column2"]    
df.to_excel("D:/tmp/test.xlsx")
print df

Which outputs the following that is inserted in the excel:

>>> 
  Column1 Column2
0   Hello    TEST
1     Est    Ting
2      Gg      ff

Solution 2:

This is the portion of my code update that allowed me to get the output I want:

for row in block.rows:
        for x, cell in enumerate(row.cells):
            print(cell.text)
            Sheet1.write(index_row, x, cell.text)
        index_row += 1

Output:

Output

Post a Comment for "Write Tables From Word (.docx) To Excel (.xlsx) Using Xlsxwriter"