module.py 1.2 KB

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