我是靠谱客的博主 动人冬天,最近开发中收集的这篇文章主要介绍使用python和xlwings合并excel文件,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

使用python和xlwings合并excel文件

20年前读书时间考了一个C语言二级,许多年都没有使用过,现在工作上遇到一个合并汇总excel文件问题,找了一个新版pyhon,网络百度,自学2周,编写了一个脚本,基本可用。来此记录已自勉!

脚本设计

  1. 合并python脚本当前目录及下级目录的xlsx文件。
  2. 只支持合并excel文件只有一个工作表,唯一sheet,只支持唯一关键字为文本的合并,为数字的因为xlwing读取到list列表格式变浮点数字,不能正确更新汇总表(原因没学懂)。
  3. 通用型合并,可适用于不同结构excel文件,只需满足上面2点的要求。
  4. 合并汇总文件,关键数据列,有效数据列,使用《配置文件.xlsx》配置。

通用配置文件.xlsx

在这里插入图片描述
序号 项目 说明
汇总文件 2019年12月二次分配表 填写汇总文件名称
关键字列 4 填写关键字列,无重复,从0开始计算,A列为0,
有效数据列 9 填写有效数据列,一般选基础薪酬列,从0开始算,A列为0,B列为1
汇总表名称 python汇总 填写添加的汇总工作表名称
原始数据表 前端 填写原始数据表名称

标题

import os
import sys
import xlwings as xw
import time


#读取当前文件夹及子文件夹下的xlsx文件
def read_filelist():
    file_list = []
    path = os.path.dirname(os.path.realpath(__file__))
    for root, dirs, files in os.walk(path, topdown=False):
        for name in files:
            if name[-4:] == 'xlsx':
                file_list.append(os.path.join(root, name))
    return (file_list)


#读取配置文件
def read_inifile():
    argv0_list = sys.argv[0].split("\")
    script_name = argv0_list[len(argv0_list) - 1]
    ini_file = sys.argv[0]
    ini_file = ini_file.replace(script_name, '配置文件.xlsx')
    if os.path.isfile(ini_file):
        app = xw.App(visible=False, add_book=False)
        ini_wb = app.books.open(ini_file)
        ini_sheet = ini_wb.sheets(1)
        ini_value = ini_sheet.range('B2:B8').value
        ini_wb.close()
    else:
        print("运行程序目录下《配置文件.xlsx》不存在,请核查!")
        sys.exit()
    return ini_value


#读取xlsx文件表第一行表头
def read_head(head_file):
    app = xw.App(visible=False, add_book=False)
    head_wb = app.books.open(head_file)
    sht = head_wb.sheets(1)
    head_range = sht.range('a1').expand('right')
    head_value = sht.range(head_range).value
    head_wb.close()
    return head_value


#合并文件
def merge_xls(file_list, key_col, data_col, sumary_sheetname):
    app = xw.App(visible=False, add_book=False)
    xls_sumwb = app.books.open(file_list[0])
    xls_sumwb.sheets.add(sumary_sheetname)
    sheet = xls_sumwb.sheets(sumary_sheetname)
    s_file=file_list.copy()
    file_list.pop(0)

    yes_value = []
    for file in file_list:
        print("正在汇总文件: "+file)
        xls_value = []
        xls_wb = app.books.open(file)
        xls_sht = xls_wb.sheets(1)
        xls_range = xls_sht.range('a1').expand('table')
        xls_value = xls_sht.range(xls_range).value
        if file != file_list[0]:
            xls_value.pop(0)
        xls_wb.close()
        for row_num in range(len(xls_value)):
            if not (xls_value[row_num][data_col] == None):
                yes_value.append(xls_value[row_num])
                
    sheet.range('a1').value = yes_value
    xls_sumwb.save()
    xls_sumwb.close()
    return s_file

def update_xls(xlsfile,source_sheet,data_sheet,keycol):
    app = xw.App(visible=False,add_book=False)
    xls_wb=app.books.open(xlsfile)
    #获取原数据
    s_sht=xls_wb.sheets(source_sheet)
    s_range=s_sht.range('a1').expand('table')
    s_value=s_sht.range(s_range).value
    #获取目标数据
    d_sht=xls_wb.sheets(data_sheet)
    d_range=d_sht.range('a1').expand('table')
    d_value=d_sht.range(d_range).value
    
    for update_index in range(len(d_value)):
        if update_index==0:
            pass
        else:
            for source_index in range(len(s_value)):
                if s_value[source_index][keycol]==d_value[update_index][keycol]:
                    d_value[update_index]=s_value[source_index]
                    write_index='a'+str(1+update_index)
                    d_sht.range(write_index).value=s_value[source_index]
                    s_value.pop(source_index)
                    break
      
    xls_wb.save()
    xls_wb.close()

#读取配置文件,读取当前目录及子目录xlsx文件,查看是否当前目前包含了配置文件当中的汇总文件
start_time = time.time()
ini_value = read_inifile()
print(ini_value)
head = []  #xls表头
ini_file = read_filelist()
is_findsumfile = False
sum_file=[]
print(ini_file)

#读取获取文件列表的表头,如果找到配置文件中的汇总文件,把汇总文件放文件列表第一个,如找不到汇总文件,提示错误退出程序
inifile_sumfile_index = -1
for filename in ini_file:
    #获取文件名(去除路径,扩展名)
    full_filename=filename.split("\")
    sub_filename=full_filename[-1].split(".")
    real_filename=sub_filename[-2]
    #如果当前文件为汇总文件,添加表头到表头第一个位置
    if ini_value[0] == real_filename:
        print(filename, ini_value[0])
        is_findsumfile = True
        inifile_sumfile_index = ini_file.index(filename)
        head.insert(0, read_head(filename))
    else:
        head.append(read_head(filename))
    
#如果找到汇总文件,把汇总文件重新放到处理文件列表第一个,如没有汇总文件,提示错误,退出程序。
if is_findsumfile == True:
    print("当前文件夹包含汇总文件!")
    inifile_sumfile = ini_file[inifile_sumfile_index]
    print(inifile_sumfile, inifile_sumfile_index)
    ini_file.remove(inifile_sumfile)
    ini_file.insert(0, inifile_sumfile)
else:
    print("汇总文件没找到,请修改《配置文件.xlsx》或在当前文件夹存放汇总文件!")
    sys.exit()

#循环判断文件列表的表头,如和汇总文件一致则保留,否则删除
#print(head[0])

head_index=0
head_total=len(head)
while head_index<head_total:
    if head[0] == head[head_index]:
        pass
        #print(ini_file[head_index]+" has the same col head.keep it in filelists waiting to combine.")
    else:
        print(ini_file[head_index]+"has a different col head . remove it from the filelist !")
        ini_file.pop(head_index)
        head_total-=1
        head_index-=1
    head_index+=1


end_time = time.time()
sum_file=merge_xls(ini_file, 0, int(ini_value[2]), str(ini_value[3]))
#print(sum_file)
update_xls(sum_file[0],str(ini_value[3]),str(ini_value[4]),int(ini_value[1]))
print("汇总合计用时" + str(end_time - start_time) + "秒")

最后

以上就是动人冬天为你收集整理的使用python和xlwings合并excel文件的全部内容,希望文章能够帮你解决使用python和xlwings合并excel文件所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(89)

评论列表共有 0 条评论

立即
投稿
返回
顶部