python - 使用 Python 在 Excel 文件中查找和替换文件名
问题描述
基于在 xlsx 文件中使用 python openpyxl 在工作表中出现的任何单元格中查找和替换文本,我尝试执行以下操作:
文件“example.xlsx”包含我想用“'path[file.xlsm]tab1'!A5”替换“'path[file.xlsx]tab1'!A5”的单元格。我试过了:
#! python3
import openpyxl
wb = openpyxl.load_workbook("example.xlsx")
ws = wb["Sheet1"]
i = 0
for r in range(1,ws.max_row+1):
for c in range(1,ws.max_column+1):
s = str(ws.cell(r,c).value)
if s != None and "xlsx" in s:
ws.cell(r,c).value = s.replace("xlsx","xlsm")
print("row {} col {} : {}".format(r,c,s))
i += 1
wb.save('targetfile.xlsx')
print("{} cells updated".format(i))
但它并没有取代任何东西。我该怎么办?
解决方案
你确定你在寻找正确的文件吗?您有两个文件 example.xlsx 和 targetfile.xlsx。更改将在 targetfile.xlsx 中看到,而不是在 example.xlsx 中。
import openpyxl
wb = openpyxl.load_workbook("mydoc.xlsx")
ws = wb['Sheet1']
i = 0
for r in range(1,ws.max_row+1):
for c in range(1,ws.max_column+1):
s = str(ws.cell(r,c).value)
if "xlsx" in s:
ws.cell(r,c).value = s.replace("xlsx","xlsm")
print("row {} col {} : {}".format(r,c,s))
i += 1
wb.save('mycode.xlsx')
print("{} cells updated".format(i))
推荐阅读
- sas - 如何阅读大型代码库
- sql - 如何正确聚合 PostgreSQL 数据库中的日期?
- python - 为什么使用 if __name__ == "__main__": main() 模式而不是将主代码放在 if 语句中?
- c# - xlsx excel无法打开文件,因为文件格式或文件扩展名无效 - c#
- azure - Azure 函数 - ConnectionString 属性尚未初始化
- c# - 基础连接已关闭。发送时发生意外错误
- r - 使用行范围创建不同的数据框
- java - 通过 POST 从 React App 发送数组到 Spring Boot
- javascript - 从对象类型的字符串值创建字符串文字类型
- php - PHP 检查 2 个变量是否相同,如测试