python数据读写操作之csv转excel
python数据读取之csv转excel从数据库读取处理后的数据格式写入csv文件的数据格式从csv转为xls的数据格式import osimport timefrom config.settings import Settingsfrom middleware.db_handler import DBHandlerfrom decimal import Decimalimport csvimpo
·
从数据库读取处理后的数据格式
写入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()
更多推荐
已为社区贡献2条内容
所有评论(0)