Python自动批量Word数据到Excel
## 问题背景
我有很多个Word文件:

里面的每个word文件中,都有数据表格

怎样把批量的word文件的表格数据提取出来,放到excel中呢

## 导入代码包
用到了python-docs这个库,需要自己安装
# pip install python-docxfrom docx import Documentimport pandas as pdimport os
## 编写解析函数
注意,当做一个普通的table解析即可,用cell(row, col)读取确定单元格的内容文本。
def parse_docfile(doc_file):doc = Document(doc_file)table = doc.tables[0]return dict(= table.cell(0, 1).text, 性别 = table.cell(0, 3).text,= table.cell(0, 5).text, 出生年月 = table.cell(0, 7).text,= table.cell(1, 1).text, 学历 = table.cell(1, 3).text,= table.cell(1, 5).text, 政治面貌 = table.cell(1, 7).text,= table.cell(2, 1).text, 专业 = table.cell(2, 4).text,= table.cell(2, 7).text,= table.cell(3, 1).text, 报考类别 = table.cell(3, 7).text,= table.cell(4, 1).text.strip(),= table.cell(5, 1).text.strip(),= table.cell(6, 1).text.strip(),= table.cell(7, 1).text.strip(),)
## 单个word的测试
parse_docfile("优秀教师选拔考试报名表/优秀教师选拔考试报名表(刘备).docx")输出结果为:
{'姓名': '刘备','性别': '男','民族': '汉','出生年月': '1956.11','参加工作时间': '1975.7','学历': '本科','籍贯': '成都','政治面貌': '蜀汉','毕业院校': '成都大学','专业': '体育','职务': '大将军','工作单位': '成都第一中学','报考类别': '语文','工作简历': '从简','工作业绩': '优秀','单位推荐意见': '同意','领导意见': '同意'}
## 结合os模块,做批量解析
初始化结果数据结构
# 列名columns = None# 数据内容datas = []
实现for循环解析
for file in os.listdir("优秀教师选拔考试报名表"):if file.endswith(".docx"):file_path = f"优秀教师选拔考试报名表/{file}"print("解析文件", file_path)data = parse_docfile(file_path)if not columns:columns = list(data.keys())datas.append([data[column] for column in columns])
程序输出结果为:
解析文件 优秀教师选拔考试报名表/优秀教师选拔考试报名表(张飞).docx解析文件 优秀教师选拔考试报名表/优秀教师选拔考试报名表(周瑜).docx解析文件 优秀教师选拔考试报名表/优秀教师选拔考试报名表(曹操).docx解析文件 优秀教师选拔考试报名表/优秀教师选拔考试报名表(小乔).docx解析文件 优秀教师选拔考试报名表/优秀教师选拔考试报名表(曹植).docx解析文件 优秀教师选拔考试报名表/优秀教师选拔考试报名表(刘备).docx
## 使用pandas输出到excel文件
df = pd.DataFrame(datas, columns = columns)df.to_excel("优秀教师选拔考试报名表.xlsx", index=False)
查看结果excel文件:

## 本代码的视频讲解
谢谢,如果对你帮助,点个赞呀!
评论
