简体   繁体   中英

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 = 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:

在此处输入图像描述

However, here is my actual output:

在此处输入图像描述

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? Any help is greatly appreciated

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

from docx.api import Document
import pandas as pd

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

for table in document.tables:
    for row in table.rows:
        text = [cell.text for 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

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 :

输出

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM