利用python批量合并excel和word内的表格

1.依赖:

python 3.9.7,python-docx==0.8.11,pandas==1.3.4 ,os

2.配置环境

pip install python-docx
pip install pandas

3.引入包

from docx import Document
import pandas as pd
import os

4.定义读取功能函数,注意:本教程只支持读取拓展名为docx的word文档,对于doc的暂不支持

#读取一个文件 并返回df数据
def readdatas(path):
    if path.endswith('.docx'):
        doc = Document(path)
        tbs = doc.tables
        tb1=tbs[0]
        data=[]
        tilte=[]
        for cell in tb1.rows[0].cells:
            tilte.append(cell.text.strip())
        for i in range(1,len(tb1.rows)):
            content=[]
            for cell in tb1.rows[i].cells:
                content.append(cell.text.strip())
            data.append(dict(zip(tilte,content)))
        return pd.DataFrame(data)
    elif path.endswith('.xls') or path.endswith('.xlsx'):
        return pd.read_excel(path,header=2,dtype='str')  

5.定义合并功能函数

# 将目标文件夹下符合条件的附件2数据合并
def merge2(path):
    data=[]
    for root,dirs,files in os.walk(path):
        for file in files:
            path=os.path.join(root,file)
            #if '附件1' in path:
                #print(path)
            data.append(readdatas(path))
    return pd.concat(data,ignore_index=True)

6.运行

if __name__=='__main__':
    path='指定文件夹路径'
    df=merge2(path) #调用函数合并
    out_name='合并后的文件名称'+'.xlsx'
    df.to_excel(out_name,index=False) #导出合并后的xlsx文件

7.其他

程序可以完善,加入判断空行等

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值