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()
相关推荐
亿牛云爬虫专家9 分钟前
Kubernetes下的分布式采集系统设计与实战:趋势监测失效引发的架构进化
分布式·python·架构·kubernetes·爬虫代理·监测·采集
蹦蹦跳跳真可爱5894 小时前
Python----OpenCV(图像増强——高通滤波(索贝尔算子、沙尔算子、拉普拉斯算子),图像浮雕与特效处理)
人工智能·python·opencv·计算机视觉
nananaij4 小时前
【Python进阶篇 面向对象程序设计(3) 继承】
开发语言·python·神经网络·pycharm
雷羿 LexChien4 小时前
从 Prompt 管理到人格稳定:探索 Cursor AI 编辑器如何赋能 Prompt 工程与人格风格设计(上)
人工智能·python·llm·编辑器·prompt
敲键盘的小夜猫5 小时前
LLM复杂记忆存储-多会话隔离案例实战
人工智能·python·langchain
高压锅_12205 小时前
Django Channels WebSocket实时通信实战:从聊天功能到消息推送
python·websocket·django
胖达不服输7 小时前
「日拱一码」020 机器学习——数据处理
人工智能·python·机器学习·数据处理
吴佳浩7 小时前
Python入门指南-番外-LLM-Fingerprint(大语言模型指纹):从技术视角看AI开源生态的边界与挑战
python·llm·mcp
UrbanJazzerati7 小时前
使用Excel制作多类别占比分析字母饼图
excel
吴佳浩7 小时前
Python入门指南-AI模型相似性检测方法:技术原理与实现
人工智能·python·llm