您的位置 首页 技术

python如何实现excel多表合并(附代码)

今天来用python实现合并多个excel为一个工作本,使用不到40行代码完成了60多张excel工作本合并为一张,大家一起来看看吧。 本篇使用的不是openpyx库,使用的使是x…

今天来用python实现合并多个excel为一个工作本,使用不到40行代码完成了60多张excel工作本合并为一张,大家一起来看看吧。

本篇使用的不是openpyx库,使用的使是xlrd,xlwt库,虽然这两库功能没法根openpyx相比,但可以操作xls结尾的旧版excel而openpyx不支持

代码

大体思路如下

  • 遍历获取根目录下的所有excel文件
  • 根据excel名称进行匹配获取某类excel
  • 创建工作本用于写入拷贝的数据
  • 每个excel都有一张Sheet1,循环遍历单元格写入创建的工作本

详细过程写在代码里面

# -*- coding: utf-8 -*-import xlrdimport xlwtimport osimport re""" 写入工作本 """def write_excel(path, write_sheet):    # 加载工作本    book = xlrd.open_workbook(path)    # 获取表单    read_sheet = book.sheet_by_name('Sheet1')    # 遍历    for row in  range(read_sheet.nrows):        for col in  range(read_sheet.ncols):            write_sheet.write(row, col, read_sheet.cell_value(row,col))            # 获取根目录下所有文件名def walk(path):  for root,dirs,names in os.walk(path):    list = []    for filename in names:        path = os.path.join(root, filename)        list.append(path)    return listif __name__ == "__main__":    # 创建工作本    write_book = xlwt.Workbook()    # 根目录    root = r'C:\mydata\generator\excel'    path_list = walk(root)    for path in path_list:        val = path.find("本专科")        if val!=-1:        # 正则匹配            ser = re.search('.*20200403(.*?).xls',path)            name = ser.group(1)            # 创建sheet            write_sheet = write_book.add_sheet(name)            # 写入            write_excel(path, write_sheet)    # 保存            write_book.save(r'本专科.xls')

感谢大家的阅读,希望大家收益多多。

本文转自:https://blog.csdn.net/youku1327/article/details/105300668

推荐教程:《python教程》

以上就是python如何实现excel多表合并(附代码)的详细内容,更多请关注24课堂在线网其它相关文章!

本文来自网络,不代表24小时课堂在线立场,转载请注明出处:https://www.24ketang.cn/89559.html

为您推荐

返回顶部