python数据读写操作之csv转excel

从数据库读取处理后的数据格式

在这里插入图片描述

写入csv文件的数据格式

在这里插入图片描述

从csv转为xls的数据格式

在这里插入图片描述

import os
import time
from config.settings import Settings
from middleware.db_handler import DBHandler
from decimal import Decimal
import csv
import pandas as pd

class FileOperate():
    def __init__(self):
        # 实例化:读取mysql操作模块
        self.MH = DBHandler()
        self.csv_path = os.path.join(Settings.test_case_path, "test_csv.csv")
        self.xls_path = os.path.join(Settings.test_case_path, "test_xls.xls")

    def setUp(self):
        pass

    def tearDown(self):
        # 关闭游标、关闭连接
        self.MH.close()
    def write_csv(self):
        # 读取csv文件
        global i
        sql = "select * from 表名 limit 20;"
        select_data = self.MH.select_sql(sql, one=False)
        number_infos = []
        # 将从数据库获取的数据进行处理存到一个列表再批量写入csv
        for i in select_data:
            print(i['id'], str(Decimal(i['amount']).quantize(Decimal('0.00'))),
                  str(Decimal(i['loan_rate']).quantize(Decimal('0.0'))), i['loan_term'])
            number_infos.append([i['id'], str(Decimal(i['amount']).quantize(Decimal('0.00'))),
                                 str(Decimal(i['loan_rate']).quantize(Decimal('0.0'))), i['loan_term']])
        with open(self.csv_path, 'w', newline='', encoding='utf-8') as csvfile:
            writer = csv.writer(csvfile)
            # 写入表头
            writer.writerow(['用户id', '金额', '税率', '借款期限'])
            # 将数据写入csv文件
            # writer.writerow(i) 写入一行
            writer.writerows(number_infos)  # 写入多行

    def csv_to_xls(self):
        # csv文件转xls格式,index = False去除索引
        csv = pd.read_csv(self.csv_path, encoding='utf-8')
        csv.to_excel(self.xls_path, sheet_name='Sheet1', index=False, float_format='%.2f')

    def xls_to_csv_(self):
        # xls文件转csv,index_col = 0从第0列开始读取
        data_xls = pd.read_excel(self.xls_path, index_col=0)
        data_xls.to_csv(self.csv_path, encoding='utf-8')

if __name__ == __main__:
    FO = FileOperate()
    FO.write_csv()
    time.sleep(5)
    FO.csv_to_xls()
Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐