【问题标题】:How to loop lists of list obtained from python-docx where each list is a table and write the tables into a seperate worksheets如何循环从 python-docx 获得的列表列表,其中每个列表都是一个表,并将表写入单独的工作表
【发布时间】:2019-05-29 15:06:27
【问题描述】:

我正在使用 python-docx 从文档中提取两个表。 我已经遍历了这些表并创建了一个列表列表。每个单独的列表代表一个表,其中我每行都有字典。每个字典都包含一个键/值对。键是表中的列标题,值是该列中该行数据的单元格内容。 在为每个表创建数据框并将每个表写入单独的 Excel 表时,我遇到了困难。

from docx.api import Document
import pandas as pd
import csv
import json
import unicodedata

document = Document('Sampletable1.docx')
tables = document.tables
print (len(tables))
big_data = []


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
        dic = dict(zip(keys, text))
        data.append(dic)
    big_data.append(data)
 print(big_data)

以上代码的输出为:

2

[[{'资产':'增长投资','目标投资组合':'66.50%','实际投资组合':'66.30%','方差':'-0.20%'},{'资产':'防御性投资','目标投资组合':'33.50%','实际投资组合':'33.70%','方差':'0.20%'}],[{'所有者':'REST Super ', 'Product': 'Superannuation', 'Type': 'Existing', 'Status': 'Existing', 'Customer 2': 'Customer 1'}, {'Owner': 'TWUSUPER TransPension', 'Product' : 'TTR Pension', 'Type': 'New', 'Status': 'New', 'Customer 2': 'Customer 1'}, {'Owner': 'TWUSUPER', 'Product': 'Superannuation', '类型':'现有','状态':'现有'}]]

如何访问上述列表?

我还尝试创建一个熊猫数据框

#write the data into a data frame
for thing in big_data:
    #print(thing)
    df = pd.DataFrame(thing)
    print(df)
    writer = pd.ExcelWriter('dftable3.xlsx', engine='xlsxwriter')
    df.to_excel(writer, sheet_name='Sheet1')
    writer.save()

我在 Excel 中获得了第一个表,但无法使用第二个表。 我希望这两个表都在同一个 excel 工作簿(dftable3.xlsx)中,但在不同的工作表中(Sheet1,Sheet2)

我附上了表格的图片。

提前致谢

【问题讨论】:

    标签: python-3.x pandas python-docx pandas.excelwriter


    【解决方案1】:

    如何访问上述列表?

    您已经这样做了,通过迭代它们或打印它们。 考虑使用漂亮打印库:

    import pprint
    pprint.pprint(big_data)
    

    我期待......不同的工作表(Sheet1,Sheet2)

    好吧,鉴于您提供的常量“Sheet1”参数,这不太可能。 这是实现这一目标的一种方法:

    writer = pd.ExcelWriter('dftable3.xlsx', engine='xlsxwriter')
    for i, thing in enumerate(big_data):
        df = pd.DataFrame(thing)
        df.to_excel(writer, sheet_name=f'Sheet{i}')
    writer.save()
    

    注意writer 的范围——它必须比每个组成部分dfs 的寿命更长。

    【讨论】:

      猜你喜欢
      • 2019-07-20
      • 2020-06-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-12
      • 2021-01-10
      • 2019-02-05
      相关资源
      最近更新 更多