关于python:python脚本合并多个excel到一个excel

65次阅读

共计 1992 个字符,预计需要花费 5 分钟才能阅读完成。

安嫂:老安,我有一些格局雷同的 excel 须要合并成一个汇总的 excel,不想一个一个复制,你懂我的意思吧?
老安:没问题,excel 我熟(熟个鬼,次要是之前做过一个次这种合并,按着博客一点一点来的,链接在这:如何疾速将多个 Excel 表格合并成一个
然而,这次啪啪打脸,安嫂给的 excel 格局不能间接转载导入,须要做一些批改,得找点材料钻研钻研。那 10,20 分钟可都不肯定能完事了,先写个脚本给安嫂安顿上,而后再钻研吧,python 代码如下:

import sys
import openpyxl
import warnings
import os
from pathlib import Path

if __name__ == '__main__':
    warnings.filterwarnings("ignore")
    if len(sys.argv) != 3:
        print("参数谬误!")
        sys.exit()
    excel_dir = Path(sys.argv[1])
    excel_summary = Path(sys.argv[2])
    if not excel_dir.exists():
        print("须要合并的 excel 文件夹门路不存在!")
        sys.exit()
    if not excel_dir.is_dir():
        print("须要合并的 excel 文件夹门路不非法!")
        sys.exit()
    if excel_summary.parent == excel_dir:
        print("excel 汇总文件不能放在须要合并的文件夹内!")
        sys.exit()
    try:
        if not excel_summary.exists():
            workbook_summary = openpyxl.Workbook(excel_summary)
            workbook_summary.create_sheet("sheet1", 0)
            workbook_summary.save(excel_summary)
            workbook_summary.close()
        workbook_summary = openpyxl.load_workbook(excel_summary)
        workbook_summary_sheetnames = workbook_summary.get_sheet_names()
        workbook_summary_first_sheet = workbook_summary.get_sheet_by_name(workbook_summary_sheetnames[0])
        workbook_summary_first_sheet_rows_count = 1
        for parent, dir_names, filenames in os.walk(excel_dir):
            for filename in filenames:
                workbook_temp_name = parent + "/" + filename
                print(workbook_temp_name)
                workbook_temp = openpyxl.load_workbook(workbook_temp_name)
                workbook_temp_sheetnames = workbook_temp.get_sheet_names()
                workbook_temp_first_sheet = workbook_temp.get_sheet_by_name(workbook_temp_sheetnames[0])
                rows = workbook_temp_first_sheet.max_row
                columns = workbook_temp_first_sheet.max_column
                for r in range(1, rows+1):
                    for c in range(1, columns+1):
                        workbook_summary_first_sheet.cell(workbook_summary_first_sheet_rows_count, c).value = workbook_temp_first_sheet.cell(r, c).value
                    workbook_summary_first_sheet_rows_count = workbook_summary_first_sheet_rows_count + 1
                workbook_temp.close()
                workbook_summary_first_sheet_rows_count = workbook_summary_first_sheet_rows_count+1
        workbook_summary.save(excel_summary)
        workbook_summary.close()
    except Exception as e:
        print(e)

用 pyinstaller 生成 exe,交差!

pip install pyinstaller
pyinstaller -F 脚本.py

正文完
 0