python使用xlrd以及xlutils.copy实现替换原有xls中特定字符为指定字符
import xlrd
from xlutils.copy import copy
import os
import re
'''
file:文件目录的路径
text:需要替换的字符
replacetext:期望替换成的字符
'''
def findAndReplace(file, text, replacetext):
wb = xlrd.open_workbook(file, formatting_info=True) # 获取xls,保留原格式
ws = wb.sheet_by_index(0) # 根据index获取sheet
rows = ws.nrows
cols = ws.ncols
newbook = copy(wb) # 复制xls
newsheet = newbook.get_sheet(0)
# 遍历每个单元格,进行替换操作
for row in range(1, rows):
for col in range(1, cols):
content = ws.cell(row, col).value
if(content != None and isinstance(content, str)): # 判断不为空且为字符
if(content.find(text) != -1): # 找到需要替换的字符
print("修改前:" + content)
print("修改后" + content.replace(text, replacetext))
newsheet.write(row, col, content.replace(text, replacetext))
# 保存新的xls以替换原有的xls
newbook.save(file)