第一次用python解决了个Excel实际问题,纪念一下。。。
1 from openpyxl import load_workbook 2 import os 3 4 sr = os.path.join(os.path.expanduser('~'), 'desktop') 5 wb = load_workbook(os.path.join(sr, 'asd.xlsx')) 6 ws = wb.active 7 col = ws.max_column 8 ws.cell(row=1, column=col + 1, value='结果') 9 dic = { 10 1: ['高度近视', 1], 11 2: ['中度近视', 2], 12 3: ['低度近视', 3], 13 0: ['正常', 0] 14 } 15 16 17 def test(x): 18 if x < -6: 19 value = dic[1] 20 elif -3 >= x >= -5.75: 21 value = dic[2] 22 elif -1 >= x >= -2.75: 23 value = dic[3] 24 else: 25 value = dic[0] 26 return value 27 28 29 def inp(row1, col1, tt): 30 ws.cell(row=row1, column=col1, value=tt) 31 32 33 for i in ws.iter_rows(min_row=2, max_row=ws.max_row, min_col=35, max_col=36): 34 row = i[0].row 35 kk = i[0].value 36 kk1 = i[1].value 37 if all([kk, kk1]): 38 t = float(kk) 39 mm1 = test(t) 40 inp(row, col + 1, mm1[0]) 41 42 x1 = float(kk1) 43 mm = test(x1) 44 inp(row, col + 2, mm[0]) 45 46 max_mm = max(mm[1], mm1[1]) 47 inp(row, col + 3, dic[max_mm][0]) 48 49 wb.save(os.path.join(sr, 'asd_do.xlsx'))