
在日常办公中我们经常需要将word文件中的数据写入Excel中,如果是手动一个一个进行复制粘贴,那将会非常的耗时且繁琐!
遇到这种问题我们首先想到就是利用编程解决,今天我分享一个word转excel的小方法!
首先我有一个word文档(结尾是docx),我想将它有规律地写入Excel,如下图:

分析
1、首先我们发现word文件的数据非常的规律,每9条可以写入Excel的一行!!
2、利用docx读取word文档的每一行数据
3、第一个9行的利用 split(“:”)将表头切出
4、利用openpyxl,将数据写入Excel
使用的第三方库与安装:
库 |
作用 |
安装 |
python-docx |
读取word文档内容 |
pip install python-docx |
openpyxl |
创建excel与写入 |
pip install openpyxl |
运行效果展示:

完整版代码:
def read_docx():count = 0wb = openpyxl.Workbook()ws = wb.activestr_ = []head_list = []docStr = Document("./word数据源/" + os.listdir("./word数据源/")[0])for paragraph in docStr.paragraphs:parStr = paragraph.textprint(parStr)if parStr!='':str_.append(parStr)head_list.append(parStr.split(":")[0])else:count += 1if count == 1:ws.append(head_list)ws.append(str_)str_.clear()else:ws.append(str_)str_.clear()wb.save("./docx转excel结果/res.xlsx")read_docx()
希望对大家有帮助,如有错误,欢迎指正
致力于办公自动化的小小程序员一枚
希望能得到大家的【一个免费关注
】!感谢!
PS此外我还写了一篇【Python将Excel文件转Word文件】:点我查看