Python-复制excel模板

**

复制excel特定的sheet页

**

-- coding: utf-8 --

2022/4/24

自动生成sheetName

使用的库

import os
import sys
import openpyxl

try:
arguments = sys.argv

# Excel_FolderPath = r"\\MFCQALABFILE1.mflex.dsbj.com\hz切片室photo temp\3、hot bar孔\2、MP hot bar--SMT出货前\2022年\11866\4月"
# Excel_Path = r"C:\Users\jl33002631\Desktop\模板.xlsx"
# Excel_Name = "模板.xlsx"
Excel_FolderPath = arguments[1]
Excel_Path = arguments[2]
Excel_Name = arguments[3]

# 打开已有的excel
Excel_workbook = openpyxl.load_workbook(Excel_Path)
# 获取日期sheet页
template_sheet = Excel_workbook['模板']
allsheets = Excel_workbook.sheetnames

# 第一步、加载文件,获取文件路径及标签
def readname():
    # 获取日期文件夹名称
    name = os.listdir(Excel_FolderPath)
    return name

def producesheetname(sheetname):
    # 判断sheet页是否已存在
    findstatus="False"
    for localsheetname in allsheets:
        if localsheetname == "模板":
            continue
        elif localsheetname == sheetname:
            findstatus="True"
            # print("sheet页已存在: "+localsheetname)
            break
        else:
            continue
    if findstatus == "False":
        # 根据获取的sheetname 创建新的sheet页
        Excel_workbook.create_sheet(sheetname) #插入到最后
        new_sheet = Excel_workbook[sheetname]
        # “日期”sheet模板复制到新增的sheet页
        for i,row in enumerate(template_sheet.iter_rows()):
            for j,cell in enumerate(row):
                new_sheet.cell(row=i+1, column=j+1, value=cell.value)
        Excel_workbook.save(Excel_Path)  # 保存数据



if __name__ == "__main__":
    name = readname()
    for i in name:
        if i == Excel_Name:
            continue
        elif i.find(".xlsx") != -1:  # 没有找到,就返回-1
            continue
        elif i.find("已完成") != -1:  # 已完成的模板不复制
            continue
        else:
            producesheetname(i)
            # print(i)
    Excel_workbook.close()
    print("成功")

except Exception as e:
print(str(e))
print(e.traceback.tb_lineno)
# 关闭
try:
Excel_workbook.Close(True)
Excel_workbook.Quit()
except:
pass

你可能感兴趣的:(python,python,开发语言)