 csv文件操作使用csv库。
可csv转excel实现更复杂的功能。
from openpyxl import load_workbook, Workbook
from openpyxl.styles import Font
def getValues(filename, sheet_name):
wb = load_workbook(filename)
wb.guess_types = True
ws = wb.active
ws = wb[sheet_name]
rows = []
nrows = ws.max_row
ncols = ws.max_column
for nrow in range(1, nrows+1):
cell = ws[nrow]
tmpList =[]
for i in range(ncols):
tmpList.append(cell[i].value)
rows.append(tmpList)
wb.close()
return rows
def saveExcel(v1, v2, filename, sheet_name):
wb = Workbook()
ws = wb.active
ws.title = sheet_name
ws.cell(1, 1, 'date')
ws.cell(1, 2, 'price')
ws.cell(1, 3, 'data')
i = 1
c2 = ''
for r1 in v1:
if r1[0]=='date':
continue
font = Font('宋体', size=11, bold=False, italic=False, strike=False, color='ff0000')
for r2 in v2:
if r2[0]=='date':
continue
if r2[0]==r1[0]:
c2 = r2[1]
font = Font('宋体', size=11, bold=False, italic=False, strike=False, color='000000')
break
ws.cell(i+1, 1, r1[0])
ws.cell(i+1, 2, r1[1])
ws.cell(i+1, 3, c2).font=font
i = i+1
wb.save(filename)
wb.close()
f1_1 = r'./analysis/1-1.xlsx'
f1_2 = r'./analysis/1-2.xlsx'
v1 = getValues(f1_1, '1-1')
v2 = getValues(f1_2, '1-2')
saveExcel(v1, v2, r'./analysis/new.xlsx', '1-3')
|