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()
相关推荐
CTA量化套保4 小时前
近期零基础量化学习:先分阶段,再用 AI 检查缺口
人工智能·python
清水白石0085 小时前
Python 死锁排查全攻略:从线程卡死到锁依赖定位与工程化修复
linux·网络·python
Elias不吃糖5 小时前
Langfuse 入门:Trace、Prompt、Dataset、Experiment、Evaluator
前端·python·prompt·langfuse
TechWayfarer5 小时前
批量查IP归属地,在线API、脚本、离线库怎么选?三种方案实测对比
网络·python·网络协议·tcp/ip
七牛开发者7 小时前
为什么 Go 很适合 AI 辅助开发?
数据库·人工智能·python·elasticsearch·log4j
河南凹凸环境艺术设计7 小时前
性价比高的民宿酒店设计企业
大数据·人工智能·python
慧都小妮子9 小时前
前端实现复杂公式计算:SpreadJS 在京东物流 Udata 平台的落地实践
javascript·数据分析·excel·数据可视化·spreadjs·前端表格控件
wuyk55510 小时前
Python 第三章:列表 List
服务器·开发语言·python
笨鸟先飞,勤能补拙10 小时前
从预测到决策:人工智能与机器学习的系统方法、工程闭环与现实边界
大数据·人工智能·windows·python·机器学习·密码学
MgArcher10 小时前
抖音a_bogus参数逆向实战:JSVMP环境模拟与Hook技术(2025最新)
javascript·爬虫·python