HandleExcelMerge2019.py 7.57 KB
import logging
import pandas as pdas
import os
import chardet
import math

from djcardrenewal.common.dbase.MysqlHelper import MysqlHelper
from djcardrenewal.common.dbase import DbConect
from djcardrenewal.common.sqlcontent import DjSql
from djcardrenewal.common.sqlcontent import CurMonthYzl
from djcardrenewal.common.string.StringBuilder import StringBuilder

print("sys config " + __name__)
log_name = './log/cwrenewal/handlexcelmerge2019.log'
log_format = '[%(asctime)s-%(filename)s-%(levelname)s:%(message)s]'
log_level = logging.DEBUG
log_mode = 'a'
logging.basicConfig(filename=log_name, format=log_format, level=log_level, filemode=log_mode)

class HandelCwExcelMergeMain:

    handleDescription = ''
    handleMonth = ''
    hmonth = ''

    db = None

    def __init__(self, handle_month):
        logging.info("init construct bean")
        self.handleDescription = "dj renewal match iccid and device location"
        self.handleMonth = handle_month
        self.hmonth = handle_month.replace('-', '')[2:6]
        self.db = MysqlHelper(DbConect.current_month_DB)

    def initCurrentMonthTable(self):
        logging.info("初始化:删除中间表")
        
    # 判断文件编码
    def detect_file_encoding(self, filename):
        with open(filename, 'rb') as f:
            content = f.read()
            result = chardet.detect(content)
            return result['encoding']

    def dealDeviceEndDateList(self):
        return True

    # 定义修改函数
    def modify_data(self, x):
        # 进行批量修改的逻辑
        if (x is None or math.isnan(x)):
            return x
        return x.replace("M{", "").replace("}", "")

    # 定义修改函数
    def modify_float_data(self, x):
        # 进行批量修改的逻辑
        if x is None:
            return 0
        current = str(x).replace("`", "").replace(' ', '')
        if current == '':
            return 0
        return current

    def exportDataToExcel(self):
        # 指定目录路径
        directory = 'D:/work_doc/000 - 审计/续费数据-商城续费/2019年电商/excelall/'

        # 获取目录中的所有文件
        files = os.listdir(directory)

        # 读取 Excel 文件并合并数据
        dataframes_121_01 = []
        dataframes_121_02 = []

        dataframes_124_01 = []
        dataframes_124_02 = []

        dataframes_208_01 = []
        dataframes_208_02 = []
        for file in files:
            print("===文件名称:", file)
            if file.startswith('支付宝') :
                if file=='支付宝账户明细.csv':
                    file_path = directory + file
                    file_encode = self.detect_file_encoding(file_path)
                    df = pdas.read_csv(file_path, delimiter=',', encoding=file_encode, skiprows=4)
                    dataframes_208_01.append(df)
                elif (file.endswith('csv')):
                    file_path = directory + file
                    file_encode = self.detect_file_encoding(file_path)
                    df = pdas.read_csv(file_path, delimiter=',', encoding=file_encode, skiprows=2)
                    dataframes_208_01.append(df)
                else:
                    file_path = directory + file
                    file_encode = self.detect_file_encoding(file_path)
                    df = pdas.read_excel(file_path, skiprows=2)
                    dataframes_208_02.append(df)
            else:
                if (file.endswith('csv')):
                    file_path = directory + file
                    file_encode = self.detect_file_encoding(file_path)
                    df = pdas.read_csv(file_path, delimiter=',', encoding=file_encode)
                    dataframes_124_01.append(df)
                else:
                    file_path = directory + file
                    file_encode = self.detect_file_encoding(file_path)
                    df = pdas.read_excel(file_path)
                    dataframes_124_01.append(df)

        # 合并所有数据
        column_name = '应结订单金额'
        merged_124_01_df = pdas.concat(dataframes_124_01, ignore_index=True)
        merged_124_01_df = merged_124_01_df.dropna(subset=[column_name])
        merged_124_01_df.to_excel('D:/work_doc/000 - 审计/续费数据-商城续费/2019年电商/excelout/1244414702All_data_2305.xlsx', index=False)
        
        column_name = '入账时间'
        # merged_208_01_df = pdas.concat(dataframes_208_01, ignore_index=True)
        # merged_208_01_df = merged_208_01_df.dropna(subset=[column_name])
        # merged_208_01_df.to_excel('D:/work_doc/000 - 审计/续费数据-商城续费/2019年电商/excelout/2088411221_zhi1data_2305.xlsx', index=False)
        
        column_name = '入账时间'
        merged_208_02_df = pdas.concat(dataframes_208_02, ignore_index=True)
        merged_208_02_df = merged_208_02_df.dropna(subset=[column_name])
        merged_208_02_df.to_excel('D:/work_doc/000 - 审计/续费数据-商城续费/2019年电商/excelout/2088411221_zhi2data_2305.xlsx', index=False)
        


    def deleteEmptyData(self):
        # 指定目录路径
        directory = 'D:/work_doc/000 - 审计/续费数据-商城续费/2019年电商/excelout/'

        # 获取目录中的所有文件
        files = os.listdir(directory)

        # 读取 Excel 文件并合并数据
        dataframes_121_01 = []
        dataframes_121_02 = []

        dataframes_124_01 = []
        dataframes_124_02 = []

        dataframes_208_01 = []
        for file in files:
            print("===文件名称:", file)
            if file.startswith('1244414702All') :
                file_path = directory + file
                dataframes_124_01 = pdas.read_excel(file_path)
                
            if file.startswith('2088411221') :
                file_path = directory + file
                dataframes_208_01 = pdas.read_excel(file_path)

        select_column = ['交易时间','微信订单号','商户订单号','应结订单金额','手续费']
        dataframes_124_01_res = dataframes_124_01[select_column]
        dataframes_124_01_res['收支类型'] = None

        select_column = ['入账时间','支付宝交易号','业务订单号','收入(+元)','支出(-元)','账务类型']
        dataframes_208_01_res = dataframes_208_01[select_column]
        dataframes_208_01_res = dataframes_208_01_res.rename(columns={'入账时间': '交易时间', '支付宝交易号': '微信订单号', '业务订单号': '商户订单号', '收入(+元)': '应结订单金额', '支出(-元)': '手续费', '账务类型': '收支类型'})

        # 批量修改某一列的数据
        dataframes_208_01_res['商户订单号'] = dataframes_208_01_res['商户订单号'].apply(self.modify_data)

        res_pd = pdas.concat([dataframes_124_01_res, dataframes_208_01_res], axis=0)
        res_pd = res_pd[res_pd['应结订单金额'] != '应结订单金额']
        res_pd['应结订单金额'] = res_pd['应结订单金额'].apply(self.modify_float_data).astype(float)
        res_pd['手续费'] = res_pd['手续费'].apply(self.modify_float_data).astype(float)

        res_pd.to_excel('D:/work_doc/000 - 审计/续费数据-商城续费/2019年电商/excelout/merge_2019All_data_2305.xlsx', index=False)



if __name__ == "__main__":
    handle_month = '2023-05'
    dedRes = False
    diRes = False
    urRes = False

    #启动初始化
    handleMain = HandelCwExcelMergeMain(handle_month)
    logging.info("start handle" + handleMain.handleDescription + ' the month:' + handleMain.handleMonth)

    # 整理数据
    #handleMain.dealTheMonthData()

    #将结果输出到excel
    # handleMain.exportDataToExcel()

    handleMain.deleteEmptyData()