| 1234567891011121314151617181920212223242526272829 |
- import json
- import pandas as pd
- def save_json(file_path, data):
- with open(file_path, 'w', encoding='utf-8') as json_file:
- json.dump(data, json_file, ensure_ascii=False, indent=4)
- def update_excel_from_json(json_file_path, excel_file_path):
- # 读取 JSON 文件
- with open(json_file_path, 'r', encoding='utf-8') as json_file:
- json_data = json.load(json_file)
- # 读取 Excel 文件
- df = pd.read_excel(excel_file_path)
- item = json_data
- product_code = item.get("货号") # 获取“货号”
- # 查找所有匹配的行索引
- matching_rows = df[df['商品编码'] == product_code].index # 获取所有匹配行号
- if not matching_rows.empty: # 检查是否有匹配的行
- for row_index in matching_rows: # 遍历所有匹配的行
- # 将其余字段的值写入到对应行的末尾
- for key, value in item.items():
- if key != "货号" and key != "色号" and key != "价格" and key != "成分": # 排除“货号”字段
- df.at[row_index, key] = value
- # 保存更新后的 Excel 文件
- df.to_excel(excel_file_path, index=False)
- print("数据已成功更新到 Excel 文件。")
|