python 读excel每行替换_python 操作excel实现替换特定内容

1 importopenpyxl2 importre3 importtraceback4

5 changeCells =06

7 #replace the special content

8 """

9 file: file path : str10 mode: type of the operatoration : int11 text: the string need to be replaceed : int or str12 replaceText: replacement Text : int or str13 """

14 defchangeData(file, mode, text, replaceText):15 #load the file(*.xlsx)

16 wb =openpyxl.load_workbook(file)17 #! deal with one sheet

18 ws =wb.worksheets[0]19 globalchangeCells20 #get rows and columns of file

21 rows =ws.max_row22 cols =ws.max_column23 changeFlag =False24 try:25 for row in range(1, rows+1):26 for col in range(1, cols+1):27 content = ws.cell(row=row, column=col).value28 if(content !=None):29 #mode1: fullmatch replacement

30 if(mode == 1):31 if(content ==text):32 ws.cell(row=row, column=col).value =replaceText33 changeFlag =True34 changeCells += 1

35 #mode2: partial replacement

36 elif(mode == 2):37 if(type(content) ==str):38 ws.cell(row=row, column=col).value =content.replace(39 text, replaceText, 1)40 changeFlag =True41 changeCells += 1

42 #mode3: partialmatch and filling

43 elif(mode == 3):44 if(type(content) ==str):45 ws.cell(row=row, column=col).value =content.replace(46 text, text+replaceText, 1)47 changeFlag =True48 changeCells += 1

49 else:50 return051 #status_1: modified success

52 if(changeFlag):53 wb.save(file)54 returnchangeCells55 #status_2: no modified

56 else:57 returnchangeCells58 #status_3: exception

59 exceptException as e:60 print(traceback.format_exc())61

62

63 #read the content of file

64 """

65 file: file path : str66 """

67 defrdxl(file):68 #load the file(*.xlsx)

69 wb =openpyxl.load_workbook(file)70 #! deal with one sheet

71 ws =wb.worksheets[0]72 globalchangeCells73 #get rows and columns of file

74 rows =ws.max_row75 cols =ws.max_column76 changeFlag =False77 cells =078 for row in range(1, rows+1):79 for col in range(1, cols+1):80 content = ws.cell(row=row, column=col).value81 print(content)82 cells += 1

83 print('cells', cells)84

85

86 if __name__ == "__main__":87 res = changeData('D:\\001.xlsx', 1, 7777, 'bug制造者')88 if(res !=None):89 print('已修改', res, '处')90 #else:

91 #print('操作失败:\n'+res)

92 rdxl('D:\\001.xlsx')

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值