【Python】实现excel文档中指定工作表数据的更新操作

在做数值计算时,个人比较习惯利用excel文档的公式做数值计算进行对比,检查异常,虽然计算量大后,excel计算会比较缓慢,但设计简单,易排错

但一般测试过程中使用到的数据都不是最终数值,会不停根据体验进行调整数值,导致计算表中使用到的数据需要时不时更新一次,为避免要用到的工作表过多不好手动复制,所以利用pandas和openpyxl写了个更新脚本,具体实现功能如下

假设数值计算需要使用A文档中的A1、A3、A4工作表,B文档中的B2、B4工作表

运行脚本后,

1.将数值计算文档中的A1、A3、A4、B2、B4复制表删除

2.重新到AB文档所在目录中找到AB文档

3.复制A1、A3、A4、B2、B4工作表内容

4.在数值计算文档中重新创建A1、A3、A4、B2、B4复制表并插入对应表内容

python 复制代码
import pandas as pd
from openpyxl import load_workbook
import json
import os


# 更新计算文档数据
class update_calculate_excel:
    def __init__(self):
        # 读取json文件,获取数据表对应信息
        self.data_json = json.loads(open('read_data.txt', 'r', encoding='UTF-8').read())
        self.file_path = self.data_json['数据路径']
        self.excel_path = self.data_json['公式路径']
        self.sheet_name = self.data_json['sheet_name']

    # 更新工作表
    def update_sheet(self):
        # 读取需要更新的工作表
        for key in self.sheet_name:
            # 拼接Excel文件绝对路径
            read_excel_doc = self.file_path + "\\" + key + ".xlsx"
            # 判断文件是否存在,不存在则退出循环
            if not os.path.exists(read_excel_doc):
                print("------------------------------------------------")
                print(read_excel_doc, "文件不存在!!!!!", )
                print("------------------------------------------------")
                continue
            for sheet_name in self.sheet_name[key]:
                # 读取所需要复制的sheet工作表
                self.read_sheet(key, sheet_name)

    # 读取工作表内容并拷贝
    def read_sheet(self, excel_name, sheet_name):
        # 拼接Excel文件绝对路径
        read_excel_doc = self.file_path + "\\" + excel_name + ".xlsx"
        # 拼接公式文档中的工作表名称
        copy_sheet_name = "{}_{}".format(excel_name, sheet_name)
        try:
            raw_data = pd.read_excel(read_excel_doc, header=None, index_col=None, sheet_name=sheet_name)
            data = raw_data.values.tolist()
            self.write_calculation_excel(copy_sheet_name, data)
            print(copy_sheet_name, "复制完成")
        except ValueError:
            print("------------------------------------------------")
            print(copy_sheet_name, "不存在!")
            print("------------------------------------------------")
            return

    # 将更新过的配置文档重新写入公式表中,实现公式表数据更新
    def write_calculation_excel(self, sheet_name, data):
        # 读取Excel文件中的所有工作表
        calculation_excel_sheet = load_workbook(self.excel_path)

        # 判断公式文档是否存在工作表
        if sheet_name in calculation_excel_sheet.sheetnames:
            # 删除公式文档内原有的工作表
            calculation_excel_sheet.remove(calculation_excel_sheet[sheet_name])

        # 创建新的空白工作表,利于数据插入
        calculation_excel_sheet.create_sheet(sheet_name)

        for row in data:
            # 循环插入数据
            calculation_excel_sheet[sheet_name].append(row)

        # 保存文件
        calculation_excel_sheet.save(self.excel_path)


if __name__ == "__main__":
    json = update_calculate_excel()
    json.update_sheet()

read_data.txt内容为存放所需数据的json格式数据

python 复制代码
{
	"数据路径": "D:\\xxx\\excel",
	"公式路径": "D:\\xxx\\数值计算.xlsx",
	"sheet_name": {
	        "Z_装备配置": ["kit_buff","kit"],
		    "Y_英雄配置": ["hero","hero_level","hero_star"],
		    "Z_专武配置": ["armscfg","arms_level","arms_star","arms_refine","arms_refines"]
		}
}

使用json格式数据是为了方便后续增加所需复制的工作表,也方便路径变更后可直接修改txt文件而非代码

相关推荐
bzmK1DTbd6 小时前
Git版本控制:Java项目中的分支管理与合并策略
java·开发语言·git
Rust研习社6 小时前
为什么 Rust 没有空指针?
开发语言·后端·rust
landyjzlai6 小时前
蓝迪哥玩转Ai(8)---端侧AI:RK3588 端侧大语言模型(LLM)开发实战指南
人工智能·python
kyriewen117 小时前
WebAssembly:前端界的“外挂”,让C++代码在浏览器里跑起来
开发语言·前端·javascript·c++·单元测试·ecmascript
我叫黑大帅8 小时前
如何通过 Python 实现招聘平台自动投递
后端·python·面试
其实防守也摸鱼9 小时前
CTF密码学综合教学指南--第九章
开发语言·网络·python·安全·网络安全·密码学·ctf
砚底藏山河9 小时前
Python量化开发:2026最佳实时股票数据API接口推荐与对比
开发语言·windows·python
AlunYegeer9 小时前
JAVA,以后端的视角理解前端。在全栈的路上迈出第一步。
java·开发语言·前端
研究点啥好呢9 小时前
专为求职者开发的“面馆”!!!摆脱面试焦虑!!!
python·面试·开源·reactjs·求职招聘·fastapi
VBAMatrix10 小时前
deepseek-v4正式接入Excel,一键生成财务分析报告
word·excel·审计·财务分析·deepseek·会计师事务所·tb工具箱