win32com python 操作wps 解决修改 表格触发关闭 其他excel的功能

win32com python 操作wps 是很方便的一个东西

之前唯一的缺点就是会关闭wps的表格。

解决思路

新开wps 进程来处理

python 复制代码
import os
import subprocess
import win32com.client as win32
import time

data = []
def get_col_value(sheet):
    # 参数设置
    row_index = 2  # 第二行
    start_column = 6  # F 列是第 6 列
    start_row = 6  # 从第 6 行开始
    # 获取最后一列和最后一行
    last_column = sheet.UsedRange.Columns.Count
    last_row = sheet.UsedRange.Rows.Count
    # 存储数据
    for col in range(start_column, last_column + 1):
        # 检查当前列第 6 行及其以下是否有数据
        has_data_below = any(sheet.Cells(row, col).Value is not None for row in range(start_row, last_row + 1))
        
        if has_data_below:  # 如果列第 6 行以下有数据
            second_row_value = sheet.Cells(row_index, col).Value  # 获取第二行的值
            # 获取第 6 行及其以下的非空值及对应行号
            column_values_with_rows = [
                {"row": row, "value": sheet.Cells(row, col).Value}
                for row in range(start_row, last_row + 1)
                if sheet.Cells(row, col).Value is not None
            ]
            column_letter = sheet.Cells(1, col).Address.split('$')[1]  # 获取列字母
            data.append({
                "column": column_letter,
                "second_row_value": second_row_value,
                "values_from_6th_row": column_values_with_rows,
            })


def get_all_excel_files(directory):
    """
    获取指定目录及其子目录中的所有 Excel 文件
    """
    excel_files = []
    for root, _, files in os.walk(directory):
        for file in files:
            if file.endswith(('.xls', '.xlsx')):
                excel_files.append(os.path.join(root, file))
    return excel_files

class WPS_handle:
    def get_curr_path(self):
        # 获取当前脚本所在目录的绝对路径
        current_dir = os.path.abspath(os.getcwd())
        # 获取所有 Excel 文件
        all_excel_files = get_all_excel_files('数据源')
        file_path = all_excel_files[0]
        
        self.root_padth = f'{current_dir}\\{file_path}'

    def get_wps_path(self):
        for root, dirs, files in os.walk("C:/"):
            if "wps.exe" in files:
                self.wps_padth = os.path.join(root, "wps.exe")
                return True
        return False

    def run_wps_processes(self):
        # 启动多个独立的 WPS 进程
        num_instances = 1  # 启动 1 个 WPS 实例
        # 启动每个进程并打开文件
        process = subprocess.Popen([self.wps_padth])  # 启动一个新的 WPS 进程
        self.app = win32.Dispatch("ket.Application")
        time.sleep(3)
        # 使用 COM 接口连接到每个 WPS 实例

    def handle_wps(self):
        # 打开不同的文件并显示在不同的窗口中
        try:
            file_paths = self.root_padth
            self.app.Visible = True  # 设置为可见,以显示 WPS 窗口
            # 打开不同的工作簿
            workbook = self.app.Workbooks.Open(file_paths)
            worksheet = workbook.Worksheets('Sheet1')
            worksheet_2 = workbook.Worksheets('Sheet2')
            worksheet_2.Cells(1, 1).Value = "姓名"
            worksheet_2.Cells(1, 2).Value = "实动工时"
            worksheet_2.Cells(1, 3).Value = "工事代码"
            worksheet_2.Cells(1, 4).Value = "分段"
            worksheet_2.Cells(1, 5).Value = "班组"
            worksheet_2.Cells(1, 6).Value = "日期"
            worksheet_2.Cells(1, 7).Value = "船号"
        
            date = worksheet.Cells(2, 2).Value
            class_ = worksheet.Cells(2, 4).Value
            get_col_value(worksheet)
            star_row = 2
            for item in data:
                for n in item['values_from_6th_row']:
                    worksheet_2.Cells(star_row, 1).Value = item['second_row_value']
                    worksheet_2.Cells(star_row, 2).Value = n['value']
                    worksheet_2.Cells(star_row, 3).Value = worksheet.Cells(n['row'], 5).Value
                    worksheet_2.Cells(star_row, 4).Value = worksheet.Cells(n['row'], 2).Value
                    worksheet_2.Cells(star_row, 5).Value = class_
                    worksheet_2.Cells(star_row, 6).Value = date
                    worksheet_2.Cells(star_row, 7).Value = worksheet.Cells(n['row'], 1).Value
                    star_row+= 1
            # 保存更改
            workbook.Save()
            # 关闭工作簿
            workbook.Close(SaveChanges=True)
        
        except Exception as e:
            print(f"发生错误: {e}")
        finally:
            # 退出每个 WPS 实例
            # app.Quit()
            del self.app
            # 结束所有启动的进程
            # for process in processes:
            #     process.terminate()
            print("操作完成")


        
    def __init__(self):
        self.root_padth = ''
        self.wps_padth = ''
        self.app = ''
        self.get_curr_path()
        self.get_wps_path()

        if self.wps_padth:
            print(f"找到 WPS 路径:{self.wps_padth}")
        else:
            print("未找到 WPS 安装路径")

        self.run_wps_processes()
        self.handle_wps()
            
if __name__ == "__main__":
    WPS_handle()
相关推荐
杨杨杨大侠11 小时前
Jev、Kev、Laya:决策模型怎么选,什么时候需要微调?
人工智能·python·agent
LOVE️YOU11 小时前
Python 在定义函数时,究竟定义的是什么?
python
段一凡-华北理工大学11 小时前
大模型应用开发 100 天:Python + LLM 从入门到精通 day26~Prompt 调试与优化——A/B 测试与效果评估
windows·python·大模型·prompt·智能体·提示词工程·高炉智能化
Minecraft红客11 小时前
以撒的结合
python·游戏·电脑·娱乐
Circ.12 小时前
Python 调试 Litellm 本地大模型接口:模型列表与对话接口实操踩坑记录
开发语言·python
风早爽太12 小时前
用 ‌Render‌ 快速部署网站和常见问题解决
python·fastapi
李航198313 小时前
给自己的图形引擎,配上了AI渲染,做设计真是太方便了
人工智能·python·计算机视觉·ai·ai编程
L@ncor13 小时前
第六章 框架开发实践 · 学习笔记(AutoGen / AgentScope / CAMEL / LangGraph)
python·框架·autogen·langgraph·agentscope
Zhou14113614 小时前
SpringSecurity_02_授权与高级功能
开发语言·python
文人sec14 小时前
玩转excel数据透视表和图表
excel