python 替换 excel 特定内容

python 替换 excel 特定内容

本文介绍用 Python 的 openpyxl 库操作 Excel(.xlsx)文件,批量替换指定内容。脚本只处理第一个工作表,修改后直接保存回原文件,使用前请先备份。

功能一览

目前实现了 3 个小功能:

  • 全字匹配替换(mode1);(如:全字匹配 yocichen, 替换成为 yociXchen)
  • 部分字符匹配替换(mode2);(如:thisisyociblog,替换成为 thisisyocichenblog)
  • 全字匹配填充(mode3);(如:yoci,替换成为yoci: a foolish),用于在字符后面添加字符

使用方法

调用 changeData(文件路径, 模式, 原内容, 替换内容) 即可完成替换,函数返回实际修改的单元格数;mode 为 1、2、3,分别对应上表中的三种模式。rdxl(文件路径) 会把工作表内容逐格打印出来,便于核对。文末的示例以 mode 1 把 D:\001.xlsx 里内容为 7777 的单元格替换为“bug制造者”,然后打印全表。

源码

import openpyxlimport reimport tracebackchangeCells = 0# replace the special content"""file: file path : strmode: type of the operatoration : inttext: the string need to be replaceed : int or strreplaceText: replacement Text : int or str"""def changeData(file, mode, text, replaceText):# load the file(*.xlsx)wb = openpyxl.load_workbook(file)# ! deal with one sheetws = wb.worksheets[0]global changeCells# get rows and columns of filerows = ws.max_rowcols = ws.max_columnchangeFlag = Falsetry:for row in range(1, rows+1):for col in range(1, cols+1):content = ws.cell(row=row, column=col).valueif(content != None):# mode1: fullmatch replacementif(mode == 1):if(content == text):ws.cell(row=row, column=col).value = replaceTextchangeFlag = TruechangeCells += 1# mode2: partial replacementelif(mode == 2):if(type(content) == str):ws.cell(row=row, column=col).value = content.replace(text, replaceText, 1)changeFlag = TruechangeCells += 1# mode3: partialmatch and fillingelif(mode == 3):if(type(content) == str):ws.cell(row=row, column=col).value = content.replace(text, text+replaceText, 1)changeFlag = TruechangeCells += 1else:return 0# status_1: modified successif(changeFlag):wb.save(file)return changeCells# status_2: no modifiedelse:return changeCells# status_3: exceptionexcept Exception as e:print(traceback.format_exc())# read the content of file"""file: file path : str"""def rdxl(file):# load the file(*.xlsx)wb = openpyxl.load_workbook(file)# ! deal with one sheetws = wb.worksheets[0]global changeCells# get rows and columns of filerows = ws.max_rowcols = ws.max_columnchangeFlag = Falsecells = 0for row in range(1, rows+1):for col in range(1, cols+1):content = ws.cell(row=row, column=col).valueprint(content)cells += 1print('cells', cells)if __name__ == "__main__":res = changeData('D:\\001.xlsx', 1, 7777, 'bug制造者')if(res != None):print('已修改 ', res, ' 处')# else:#     print('操作失败:\n'+res)rdxl('D:\\001.xlsx')

注意事项

  • 脚本保存时直接覆盖原文件,运行前请先备份 Excel 文件。
  • mode 1 是整格精确匹配,只有单元格内容与原内容完全相等时才替换。
  • mode 2、mode 3 只对文本单元格生效,数字、日期等非文本单元格不会被替换。
  • 脚本只处理第一个工作表(worksheets[0]),多表文件请自行调整。

本文转载自:https://www.cnblogs.com/yocichen/p/11693243.html

留下评论