1 回答
TA贡献1826条经验 获得超6个赞
此代码应该会得到您要查找的结果。它打开 csv 和 excel 文件,并根据 csv 中的关键列更新 excel 文件。如果找不到匹配的键列,它会附加一行。
# Create CSV for test
cdata = '''
Col1 Col2 Col3
typ1 asdf 1300
typ2 b14f 150
typ3 a8-j 11
'''.strip()
with open ('working.csv', 'w') as csvfile:
csvfile.write(cdata)
###################### Main Script ##########################
import csv
import openpyxl
logfile = 'logbook.xlsx'
wb = openpyxl.load_workbook(logfile)
ws = wb.worksheets[0]
curcol = 6 # SEP1
with open ('working.csv', 'r') as csvfile:
infile = csv.reader(csvfile, delimiter=' ')
for i, row in enumerate(infile):
if i==0: continue # skip headers
for xr in range(3, ws.max_row+1): # check excel sheet
if ws.cell(xr,1).value == row[0] and ws.cell(xr,2).value == row[1]: # key columns match
ws.cell(xr,curcol).value = float(row[2]) # copy csv value
break # found entry
else: # did not find entry, must add row
ws.cell(xr+1, 1).value = row[0]
ws.cell(xr+1, 2).value = row[1]
ws.cell(xr+1, curcol).value = float(row[2])
wb.save('logbookNew.xlsx')
前
后
添加回答
举报