将 Word 文档中的表格细栏,提取一些栏目的信息到 Excel 表格中。
将其中的日期格式处理成标准格式。
Word 文档信息:
输出的 Excle 格式信息:
代码实现
这类格式规整的文件整理非常适合用Python来执行,下面就是代码和注释。
#导入需要的库docx
#No module named 'Document' 出现这个错误的话
# 安装依赖包 pip install Python-docx
#
from docx import Document
import datetime
from openpyxl import Workbook
# 创建excle表格
wb = Workbook()
# 表里面创建sheet
sheet = wb.active
# 创建标题
header = ['序号', '时间', '其他1', '标题', '文件1','文件2', '备注']
# 将标题添加到sheet
sheet.append(header)
# 指定输入文件存放的路径
path = r'/Users/haha/Desktop/Word-to-Excel.docx'
# 读取文件
document = Document(path)
# 读取word中的所有表格
tables = document.tables
# 在全局放一个变量用来计数,设置序号开始为0
n = 0
# 循环遍历所有table table0 = tables[0]
for j in range(len(tables)):
# 从第0行遍历
i = 0
try:
# 日期 表的第一行,第一列(0,0)
# 获取 table[0].cell(1,0) 的文件内容
date = tables[j].cell(i, 0).text
if '/' in date:
# 时间我们获取的是 2/1 这种 日/月的形式
# 转化成 YYYY-MM-DD格式,而这利用到datetime包的strptime和strftime函数
# strptime: 解析字符串中蕴含的时间
# strftime: 转化成所需的时间格式
date = datetime.datetime.strptime(date, '%m/%d').strftime('2020-%m-%d')
else:
date = '-'
# 其他1
other = '其他'
# 标题 获取第2行第1列内容 (1,0)
title = tables[j].cell(i+1, 1).text.strip()
# 文件1 获取第3行第3列内容 (2,2)
dfn1 = tables[j].cell(i+2, 2).text.strip()
# 文件2 获取第1行第4列内容 (0,3)
dfn2 = tables[j].cell(i, 3).text.strip()
n += 1
print(n, date,other, title, dfn1,dfn2)
row = [n,date,other,title,dfn1,dfn2,' ']
# 添加数据到sheet
sheet.append(row)
except Exception as error:
# 捕获异常,也可以用log写到日志里方便查看和管理
print(error)
continue
# 保存excel文件
wb.save(r'/Users/haha/Desktop/20200516.xlsx')
# 输出结果:
1 2020-05-14 其他 Python1 自动化1 办公1
2 2020-05-15 其他 Python2 自动化2 办公2
3 2020-05-16 其他 Python3 自动化3 办公3
4 2020-05-17 其他 Python4 自动化4 办公4
5 2020-05-18 其他 Python5 自动化5 办公5
6 2020-05-19 其他 Python6 自动化6 办公6
Excel 文件内容:
原文链接