用 openpyxl 处理 xlsx 文件

openpyxl 是一个用来处理 excel 文件的 python 代码库, 安装什么略过不提, 只说一个简单操作的例子

  1. 例子

    有这么一个表

    高压/低压(实验组)高压/低压(对照组)
    156/99110/70
    124/83119/71
    103/78100/60
    150/100114/78
    150/100109/74
    100/76112/65
    130/90130/77
    174/105121/72
    109/85129/84
    140/100128/80
    120/80
    122/73
    120/70
    107/80
    110/70
    115/73
    110/61
    127/80
    110/70
    108/79
    114/78
    118/71

    需要把高压低压分开两列来整, 手动写要累死狗, 上万的数据, 于是祭出Python大法

  2. 烂码

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import re

import openpyxl

file = "工作簿2.xlsx"
wb = openpyxl.load_workbook(file)
ws = wb.get_sheet_by_name("Sheet1")

rows = ws.max_row
cols = ws.max_column

p = re.compile("[0-9]+/[0-9]+")

for row in range(1, rows + 1):
    i = 0
    for col in range(1, cols + 1):
        v = str(ws.cell(row=row, column=col).value)
        if re.search(p, v):
            lst = v.split("/")
            ws.cell(row=row, column=col + i + cols).value = int(lst[0])
            i += 1
            ws.cell(row=row, column=col + i + cols).value = int(lst[1])
        else:
            i += 1

ws = wb.get_sheet_by_name("Sheet2")

for row in range(1, rows + 1):
    i = 0
    for col in range(1, cols + 1):
        v = str(ws.cell(row=row, column=col).value)
        if re.search(p, v):
            lst = v.split("/")
            ws.cell(row=row, column=col + i + cols).value = int(lst[0])
            i += 1
            ws.cell(row=row, column=col + i + cols).value = int(lst[1])
        elif re.search(re.compile("[0-9+/.+]"), v):
            lst = v.split("/")
            # print(lst)
            ws.cell(row=row, column=col + i + cols).value = int(lst[0])
            i += 1
            ws.cell(row=row, column=col + i + cols).value = lst[1]
        elif v == "未记录":
            ws.cell(row=row, column=col + i + cols).value = "未记录"
            i += 1
            ws.cell(row=row, column=col + i + cols).value = "未记录"
        else:
            i += 1

wb.save("test.xlsx")

享受生活即可

结果长这样

高压/低压(实验组)高压/低压(对照组)高压(实验)低压(实验)高压(对照)低压(对照)
156/99110/701569911070
124/83119/711248311971
103/78100/601037810060
150/100114/7815010011478
150/100109/7415010010974
100/76112/651007611265
130/90130/771309013077
174/105121/7217410512172
109/85129/841098512984
140/100128/8014010012880
120/8012080
122/7312273
120/7012070
107/8010780
110/7011070
115/7311573
110/6111061
127/8012780
110/7011070
加载评论