如何用Python更新Excel单元格中的JSON数据并保存回文件
完整实现:修改XLSM中JSON数据并写回
核心思路
直接用Pandas操作Excel列,省去转Numpy数组的冗余步骤;编写通用函数处理JSON内容的批量修改,最后通过支持XLSM格式的引擎写回文件,同时保留原文件的所有列和宏结构。
完整代码实现
import json import pandas as pd def modify_text_content(json_str, replace_mapping): """ 修改JSON中所有TEXT类型item的content字段 :param json_str: 原始JSON字符串 :param replace_mapping: 字符串替换规则字典,key为原字符串,value为目标字符串 :return: 修改后的JSON字符串,解析失败则返回原字符串 """ try: json_data = json.loads(json_str) # 遍历所有sections for section in json_data.get("sections", []): # 遍历当前section下的所有items for item in section.get("items", []): if item.get("type") == "TEXT" and "content" in item: # 应用替换规则,未匹配到则保留原内容 item["content"] = replace_mapping.get(item["content"], item["content"]) # 格式化输出JSON,保持可读性 return json.dumps(json_data, indent=2, ensure_ascii=False) except json.JSONDecodeError: # 解析失败时返回原内容,避免破坏数据 return json_str if __name__ == "__main__": # 1. 读取完整工作表(保留所有列,避免丢失数据) # 需提前安装openpyxl:pip install openpyxl df = pd.read_excel("file.xlsm", sheet_name="Sheet1", engine="openpyxl") # 2. 定义需要替换的字符串规则 replace_rules = { "String to be changed": "已修改的文本内容1", "Another string to be changed": "已修改的文本内容2" # 可根据需求添加更多替换规则 } # 3. 批量处理JSON列(假设JSON数据存储在Q列,根据实际列名调整) df["Q"] = df["Q"].apply(lambda x: modify_text_content(x, replace_rules)) # 4. 写回XLSM文件(保留宏,使用openpyxl引擎) df.to_excel("modified_file.xlsm", sheet_name="Sheet1", index=False, engine="openpyxl")
关键注意事项
- 保留原文件结构:读取时不要限制
usecols,否则会丢失其他列数据;若仅需修改特定列,读取完整表后单独处理目标列即可。 - JSON解析容错:添加
JSONDecodeError捕获,避免因个别单元格JSON格式错误导致程序中断。 - XLSM格式支持:必须使用
openpyxl引擎读写XLSM文件,默认引擎不支持宏格式;若未安装,执行pip install openpyxl安装。 - 自定义修改逻辑:可根据需求修改
modify_text_content函数,比如使用正则表达式替换、动态生成新内容等。
内容的提问来源于stack exchange,提问作者Dominic Order
相关产品推荐
相关产品推荐

