这里只是对openpyxl这个模块修改Excel功能做一下记录,暂时没有对这个模块进行研究。

    工作中遇到需要对Excel中某一列的多行单元格添加相同的内容,刚开始的时候是自己手动添加,添加了一些后发现手动操作太慢了,也太无聊了。想起之前同事也遇到过相同的事情,后来写了个自动化解决了,于是直接找同事要了之前的自动化代码,稍加修改,为己所用:

 1 # coding=utf-8
 2 
 3 from openpyxl import load_workbook
 4 
 5 inwb = load_workbook("entrust.xlsx")
 6 add_data = ',\n"entrust.apply.baofu.monitor": 0,\n"entrust.resend.baofu.monitor": 0,\n"entrust.tracking.baofu.monitor": 0,\n"entrust.verify.baofu.monitor": 0\n}'
 7 
 8 for sheetName in inwb.get_sheet_names():
 9     # if not sheetName.isdigit():
10     #     continue
11     sheet = inwb[sheetName]
12     # 修改第80列第29-117行的内容
13     for rownum in range(29, 118):
14         oldstr = sheet.cell(row=rownum, column=80).value
15         print(type(oldstr))
16         print(oldstr)
17         if oldstr:
18             # 根据需要截取原单元格里面的内容与需要添加的内容进行拼接
19             newstr = oldstr[:-2] + add_data
20             print(newstr)
21             # 往单元格中写入拼接后的新字符串内容
22             sheet.cell(row=rownum, column=80).value = newstr #if oldstr != "None" else ""
23         else:
24             pass
25 
26 
27 # 将excel重命名保存
28 inwb.save("entrust1.xlsx")
View Code

相关文章: