【python】读取EXCEL数据并生成py文件

表格内容
在这里插入图片描述

import os
import pandas as pd


class DataHandle:
    def __init__(self):
        self.currentPath = os.path.dirname(__file__)
        self.excelPath = self.currentPath + "/reFile.xlsx"
        self.reExcelFile = pd.read_excel(self.excelPath, sheet_name=None, engine='openpyxl')

    def writePyFile(self):
        tempName = ''
        number = []
        for sheetName, sheetData in self.reExcelFile.items():

            for rowIndex, row in sheetData.iterrows():

                if len(number) > 0 and row['id'] not in number:
                    self.finalData(f"{self.currentPath}/temp.py", f"{self.currentPath}/{tempName}.py", tempName)

                tempName = row['id']

                if len(number) == 0 or tempName not in number:
                    self.preData(f"{self.currentPath}/temp.py")

                writeContent = f"""                                       
    def step(self):
        path1 = "{self.currentPath}/{row['preText']}"
        path2 = "{self.currentPath}/{row['preText']}.jpeg"
        print("{row['text']}")
        """

                with open(f"{self.currentPath}/temp.py", 'a', encoding='UTF-8') as fileWriteContent:
                    fileWriteContent.write(writeContent)

                number.append(row['id'])

            self.finalData(f"{self.currentPath}/temp.py", f"{self.currentPath}/{tempName}.py", tempName)


    def preData(self, filePath):
        headContent = f"""
import os
import pandas as pd

class Temp:
    def __init__(self):
        self.type = 12         
"""
        with open(filePath, 'w', encoding='UTF-8') as fileWriteHead:
            fileWriteHead.write(headContent)

    def finalData(self, filePath, reFilePath, replaceName):
        finalContent = f"""
if __name__ == "__main__":
    test()
    """
        with open(filePath, 'a', encoding='UTF-8') as fileWriteFinal:
            fileWriteFinal.write(finalContent)
        with open(filePath, 'r', encoding='UTF-8') as readFile:
            content = readFile.read()

        content = content.replace('Temp', replaceName)
        with open(filePath, 'w', encoding='UTF-8') as writeFile:
            writeFile.write(content)

        os.rename(filePath, reFilePath)

DataHandle().writePyFile()

最终效果:
在这里插入图片描述

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值