Python Forum
Write tables from Word (.docx) to Excel (.xlsx) using xlsxwriter
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Write tables from Word (.docx) to Excel (.xlsx) using xlsxwriter
#1
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 = Document('/Users/xxx/Documents/xxx/Clauses Sample - Copy v1 - for merge.docx')
tables = document.tables

wb = xlsxwriter.Workbook('C:/Users/xxx/Documents/xxx/test clause retrieval.xlsx')
Sheet1 = wb.add_worksheet("Compliance")
index_row = 0

print(len(tables))

for table in document.tables:
data = []
keys = None
for i, row in enumerate(table.rows):
    text = (cell.text for cell in row.cells)

    if i == 0:
        keys = tuple(text)
        continue
    row_data = dict(zip(keys, text))
    data.append(row_data)
    #print (data)
    #big_data.append(data)
    Sheet1.write(index_row,0, str(row_data))      
    index_row = index_row + 1

print(row_data)

wb.close()
This is my desired output: [Image: 9qnbw.png]

However, here is my actual output: [Image: vpXej.png]

I am aware that my current output produces a list of string instead.

Is there anyway that I can get my desired output using xlsxwriter?
Reply
#2
Don't zip the keys and text into a dict. Put them into the columns and rows as shown here.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  tables in Excel MaartenRo 3 538 Jan-06-2024, 03:46 PM
Last Post: deanhystad
  no module named 'docx' when importing docx MaartenRo 1 888 Dec-31-2023, 11:21 AM
Last Post: deanhystad
  python Read each xlsx file and write it into csv with pipe delimiter mg24 4 1,466 Nov-09-2023, 10:56 AM
Last Post: mg24
  Replace a text/word in docx file using Python Devan 4 3,446 Oct-17-2023, 06:03 PM
Last Post: Devan
  How do I write all csv records to Excel ? Revox 2 962 Mar-29-2023, 03:53 PM
Last Post: deanhystad
  Reading data from excel file –> process it >>then write to another excel output file Jennifer_Jone 0 1,113 Mar-14-2023, 07:59 PM
Last Post: Jennifer_Jone
  Working with Excel and Word, Several Questions Regarding Find and Replace Brandon_Pickert 4 1,569 Feb-11-2023, 03:59 PM
Last Post: Brandon_Pickert
  how to read txt file, and write into excel with multiply sheet jacklee26 14 10,039 Jan-21-2023, 06:57 AM
Last Post: jacklee26
  Openpyxl manipulate excel write formula SamLiu 0 1,062 Nov-04-2022, 03:00 PM
Last Post: SamLiu
  python-docx regex: replace any word in docx text Tmagpy 4 2,246 Jun-18-2022, 09:12 AM
Last Post: Tmagpy

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020