当前位置: 首页 > 后端技术 > Python

Python使用xlrd和xlutils.copy将原xls中的特定字符替换为指定字符

时间:2023-03-26 12:00:31 Python

Python使用xlrd和xlutils.copy将原xls中的特定字符替换为指定的字符被替换'''deffindAndReplace(file,text,replacetext):wb=xlrd.open_workbook(file,formatting_info=True)#获取xls,保持原格式ws=wb.sheet_by_index(0)#根据索引获取sheet行=ws.nrowscols=ws.ncolsnewbook=copy(wb)#复制xlsnewsheet=newbook.get_sheet(0)#遍历每个单元格,对rowinrange(1,rows)进行替换操作:forcolinrange(1,cols):content=ws.cell(row,col).valueif(content!=Noneandisinstance(content,str)):#判断不为空且为字符if(content.find(text)!=-1):#查找需要替换的字符print("修改前:"+content)print("修改后"+content.replace(text,replacetext))newsheet.write(row,col,content.replace(text,replacetext))#保存新的xls替换原来的xlsnewbook.save(file)