python处理数据库导出的csv文件转成xlsx格式的Excel

可以合成多个文件到一个excel中,具体代码实现

import numpy as np
import pandas as pd

myDownloadPath = '/Users/varrant/Downloads/'
file1 = myDownloadPath + 'pay_flow_ll.csv'      # 待转化的源文件
file2 = myDownloadPath + 'pay_flow_ll (1).csv'  # 待转化的源文件
file3 = myDownloadPath + 'pay_flow_ll (2).csv'  # 待转化的源文件
outfile = myDownloadPath + 'pay_flow_ll.xlsx'   # 转化后的excel所处的位置与文件名


def csv_to_xlsx_pd():
    csv1 = common_fn(file1)
    csv2 = common_fn(file2)
    csv3 = common_fn(file3)
    writer = pd.ExcelWriter(outfile)
    pd.set_option('max_colwidth', 150)
    csv1.to_excel(writer, sheet_name='支付')
    csv2.to_excel(writer, sheet_name='退款')
    csv3.to_excel(writer, sheet_name='拒付')
    writer.save()
    writer.close()


def common_fn(file):
    return pd.read_csv(file, delimiter=';', quotechar='"',
                       dtype={'原单连连订单号': str, '连连订单号': str, '退款订单号': str, '拒付id': str, '原单渠道流水号': str},
                       encoding='utf-8')


if __name__ == '__main__':
    csv_to_xlsx_pd()
    print("转化完成!!!\nExcel文件所处位置:" + str(outfile))

推荐阅读更多精彩内容