?
直接上代码:
# -*- coding:utf-8 -*-
import csv,os
from pandas.tests.io.excel.test_openpyxl import openpyxl
class CsvHandller:
def __init__(self,filename):
self.filename=filename
def read(self, line=None):
'''
:param line: 默认为None,如何line=int,则读取指定行的数据
:return: 返回所有数据或者指定行数据
'''
with open(self.filename, "r", encoding="GBK") as file:
reader = csv.reader(file)
result = []
for index, row in enumerate(reader,1):
if not line:
result.append(row)
elif int(line)==index:
return row
file.close()
return result
def writer_csv_data(self,data):
'''
:param data: 向csv写入所有数据
:return: 返回None
'''
with open(self.filename,mode='w+',encoding='GBK') as file:
writer=csv.writer(file)
writer.writerows(data)
file.close()
return
def write(self,num,sheet_name:str, data):
'''
:param num: 指定sheet的位置,sheet初始位置为0
:param sheet_name: 创建一个新的sheet
:param data: 向sheet中写入的数据,目前只支持list
:return: 返回None
'''
# 创建一个Workbook对象
if os.path.exists(self.filename):
wb = openpyxl.load_workbook(self.filename)
else:
wb = openpyxl.Workbook()
# 获取指定sheet
sheet = wb.create_sheet(title=sheet_name,index=num)
for row,element in enumerate(data,1):
for column,value in enumerate(element,1):
# 根据行号和列号修改单元格,默认是从第一行第一列写入
sheet.cell(row,column).value = value
# 保存excel
wb.save(self.filename)
# 关闭excel
wb.close()
return
if __name__ == '__main__':
csvhandler=CsvHandller('../data/1.csv')
data=csvhandler.read()
print(data)
# csvhandler=CsvHandller('../data/2.csv')
# csvhandler.writer_csv_data(data)
filename='../data/2.xlsx'
csvhandler=CsvHandller(filename)
if os.path.exists(filename):
os.remove(filename)
csvhandler.write(0,'数据A',data)
csvhandler.write(1,'数据B',data)
csvhandler.write(2,'交叉数据C',data)
|