关于自动化提取word中表格信息的方法(python自动化办公)

150 阅读1分钟

关于自动化提取word中表格信息的方法

本文已参与「新人创作礼」活动,一起开启掘金创作之路。 最近工作中需要提取word中表格的特定信息,采用python写了一个小的脚本,留在此处供大家参考。

import docx

data = docx.Document(r"C:\Users\86180\Desktop\埋深\5.地下水埋深逐日监测成果表.docx")

all = []

for table in data.tables:
    table_sigle = {}
    for r in table.rows:
        for cell in r.cells:
            if cell.text[:2] == "东经":
                table_sigle["东经"] = cell.text[3:]
            elif cell.text[:2] == "北纬":
                table_sigle["北纬"] = cell.text[3:]
            elif cell.text[:5] == "平均埋深:":
                table_sigle["平均埋深"] = cell.text[5:]
    all.append(table_sigle)


print(all)
            
k = {"东经":[],"北纬":[],"平均埋深":[]}
key = ["东经","北纬","平均埋深"]

result = [k[s].append(point[s]) for point in all for s in key]

import pandas as pd
result = pd.DataFrame(k)
result.to_excel("ms1.xlsx")

ps:docx可以很好的进行word文档的解析,可以把word当做对象,word中的表格就是tables对象,利用Document读取word后,利用tables属性就可以搞出来。word对应的文件是横页的表格。