pyqt QAxWidget 读写Excel文件

QaxWidget相比openpyxl 的方式区别是提供了图形界面,excel的输入修改不用再编写代码.activeX技术是个过时的技术,发挥下余热. 

# -*- coding: utf-8 -*-
from PyQt5.QAxContainer import QAxWidget
from PyQt5.QtWidgets import QWidget, QVBoxLayout, QPushButton, QFileDialog
from PyQt5 import QtWidgets
from pyqtconsole.console import PythonConsole
import os
import getpath
import myglobal
class Window(QWidget):

    def __init__(self, *args, **kwargs):
        super(Window, self).__init__(*args, **kwargs)
        layout = QVBoxLayout(self)
        self.ax = QAxWidget(self)#"Excel.Application",self)
        # self.ax = AxWidget()#QAxWidget("{000208DB-0000-0000-C000-000000000046}",self)#book
        # self.excel.setProperty("Visible", True);
        # self.excel=Application()
        # print(dir(self.axWidget))
        # self.axWidget.initialize(self.excel._dispobj_)#a._dispobj_._oleobj_
        h=QtWidgets.QHBoxLayout()
        h.addWidget(QPushButton('打开excel', self, clicked=self.onOpenWord))
        h.addWidget(QPushButton('getdata', self, clicked=self.getdata))
        h.addWidget(QPushButton('save as', self, clicked=self.saveas))
        h.addWidget(QPushButton('calc', self, clicked=self.calc))
        # h.addWidget(QPushButton('quit', self, clicked=self.quitWord))
        # self.console = interpreter.TerminalPython(self, mainw=self, app=QtWidgets.qApp)

        self.console=PythonConsole()
        self.console.push_local_ns('app', QtWidgets.qApp)
        self.console.push_local_ns('mainw', self)
        self.console.eval_queued()
        self.console.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Fixed)
        self.console.resize(self.console.width(),200)
        h.addWidget(self.console)
        layout.addLayout(h)
        layout.addWidget(self.ax)
        # self.workbooks = self.excel.querySubObject("Workbooks")
        self.ax.setControl(os.path.join(getpath.getpath(),"重量法.XLSX"))
        # self.excel=self.ax.querySubObject("Application")
    def getdata(self):
        s1=self.ax.querySubObject("Activesheet")
        c11=s1.querySubObject("Cells(1,1)")
        print(c11.property("Value"))
        pass
    def getCellValue(self,i,j):
        s1=self.ax.querySubObject("Activesheet")
        c11=s1.querySubObject(f"Cells({i},{j})")
        return(c11.property("Value"))
    def setCellValue(self,i,j,value):
        # 'ws=self.ax.querySubObject("Worksheets")
        # 's1=ws.querySubObject("Item(int)",1)
        s1=self.ax.querySubObject("Activesheet")
        c11=s1.querySubObject(f"Cells({i},{j})")
        c11.setProperty("Value",value)
    def getDblOne(self,i, jstr):
        if self.getCellValue(i, jstr)== "":
            return 1.0
        else:
            r=self.getDbl(i, jstr)
            if r==0:
                r=1.0
            return r
    def getDbl(self,i, jstr):
        s1=self.getCellValue(i, jstr)
        r=myglobal.myfloat(s1)
        # print(s1,r)
        return r
    def save_zhongliang(self,ffbh, ejff, ejjs):
        # Dim r As Range
        # If ActiveSheet Is Nothing Then
        #  Exit Sub
        # End If
        # Set r = ActiveSheet.UsedRange
        # Dim f As String
        # Dim m As String
        # Dim tpbh As String, syy As String, ysry As String, syyqm As String, yqbh As String
        # Dim row_num As Integer
        row_num = self.getRowCount()
        # Dim sid As String
        # Dim i As Integer
        ActiveSheet=self.ax.querySubObject("Activesheet")
        i=7
        while(i<=row_num):
            sid=ActiveSheet.querySubObject(f"Cells({i},{"A"})").property("Value")
            if  sid!= "" and sid!=None:
                break
            i+=1
        f = ActiveSheet.querySubObject(f"Cells({2},{"E"})").property("Value")#ActiveSheet.Cells(2, "E").Value
        if f==None:
            f=""
        ffbh = ActiveSheet.querySubObject(f"Cells({1},{"B"})").property("Value")#ActiveSheet.Cells(1, "B").Value
        syy = ActiveSheet.querySubObject(f"Cells({1},{"K"})").property("Value")#ActiveSheet.Cells(1, "K").Value
        ysry = ActiveSheet.querySubObject(f"Cells({1},{"N"})").property("Value")#ActiveSheet.Cells(1, "N").Value
        syyqm = syy
        yqbh = ActiveSheet.querySubObject(f"Cells({1},{"H"})").property("Value")#ActiveSheet.Cells(1, "H").Value
        item_name = ActiveSheet.querySubObject(f"Cells({2},{"B"})").property("Value")#ActiveSheet.Cells(2, "B").Value
        ActiveSheet.querySubObject(f"Cells({3},{"P"})").setProperty("Value",item_name)#ActiveSheet.Cells(3, "P").Value = item_name
        # Dim row As Integer
        # Dim output_folder As String
        # Dim at As Integer
        # Dim fname As String
        i=row_num
        while i>=1:
            v=ActiveSheet.querySubObject(f"Cells({i},{"A"})").property("Value")
            print(i,v)
            if v!=None and v!="":
                row = i
                break
            i=i-1
        r=ActiveSheet.querySubObject("UsedRange")
        print(row,r.querySubObject("Rows").property("Count"))
        while row + 1 <= r.querySubObject("Rows").property("Count"):
            print(row+1,r.querySubObject("Rows").property("Count"))
            # ActiveSheet.Rows(row + 1).Delete
            ActiveSheet.querySubObject(f"Rows({row+1})").dynamicCall("Delete()")
        at = 1
        ActiveSheet.querySubObject(f"Cells({row+1},{at})").setProperty("Value","ffbh&" + ffbh)#ActiveSheet.Cells(row + 1, at).Value = "ffbh&" + ffbh
        ActiveSheet.querySubObject(f"Cells({row+2},{at})").setProperty("Value","syy&" + syy)# ActiveSheet.Cells(row + 2, at).Value = "syy&" + syy
        ActiveSheet.querySubObject(f"Cells({row+3},{at})").setProperty("Value","ysry&" + ysry)# ActiveSheet.Cells(row + 3, at).Value = "ysry&" + ysry
        ActiveSheet.querySubObject(f"Cells({row+4},{at})").setProperty("Value","yqbh&" + yqbh)# ActiveSheet.Cells(row + 4, at).Value = "yqbh&" + yqbh
        ActiveSheet.querySubObject(f"Cells({row+5},{at})").setProperty("Value","syyqm&" + syyqm)# ActiveSheet.Cells(row + 5, at).Value = "syyqm&" + syyqm
        ActiveSheet.querySubObject(f"Cells({row+6},{at})").setProperty("Value","dict0&" + f)# ActiveSheet.Cells(row + 6, at).Value = "dict0&" + f
        ActiveSheet.querySubObject(f"Cells({row+6},{at})").setProperty("Value","系数")# ActiveSheet.Cells(row + 6, at + 1).Value = "Ñõ»¯ÎïϵÊý"
        ActiveSheet.querySubObject(f"Cells({row+7},{at})").setProperty("Value","ejff&" + ejff)# ActiveSheet.Cells(row + 7, at).Value = "ejff&" + ejff
        ActiveSheet.querySubObject(f"Cells({row+7},{at})").setProperty("Value","二级方法")# ActiveSheet.Cells(row + 7, at + 1).Value = "¶þ¼¶·½·¨"
        ActiveSheet.querySubObject(f"Cells({row+8},{at})").setProperty("Value","ejfxjs&" + ejjs)# ActiveSheet.Cells(row + 8, at).Value = "ejfxjs&" + ejjs
        ActiveSheet.querySubObject(f"Cells({row+8},{at})").setProperty("Value","二级分析技术")# ActiveSheet.Cells(row + 8, at + 1).Value = "¶þ¼¶·ÖÎö¼¼Êõ"
        output_folder = "d:\\"
        # 'output_folder = "\\10.0.114.230\»¯Ñ§·ÖÎöÊÒ\ÒÇÆ÷²É¼¯\EMGA930_test\930"
        # output_folder = "\\10.0.114.230\»¯Ñ§·ÖÎöÊÒ\ÒÇÆ÷²É¼¯\caiji\cl\zhongliang"
        if sid == "":
            fname = "tmp"#Format(Now, "yyyymmdd hhmmss")
        else:
            fname = sid
        filename=os.path.join(output_folder,fname)
        self.ax.dynamicCall("SaveAs(const QString&)",filename)
    def saveas(self):
        self.save_zhongliang("","","")
        return
        filename=os.path.join(getpath.getpath(),"a1.xlsx")
        self.ax.dynamicCall("SaveAs(const QString&)",filename)
        # workbook->synamicCall(“Close(Boolean)”, false); //! 关闭文件
    def getRowCount(self):
        s1=self.ax.querySubObject("Activesheet")
        r=s1.querySubObject("UsedRange")
        rows=r.querySubObject("Rows")
        return rows.property("Count")
    def runCalc(self):
        excel=self.ax.querySubObject("Application")
        excel.dynamicCall("Run(const QString&)","mycalc")
    def calc(self):
        print("calc")
        # 'Dim f As Double, m2 As Double, m1 As Double, m0 As Double, m3 As Double, m4 As Double, m5 As Double
        # 'Dim row_num As Integer
        # 'Dim mass As Double, V1 As Double, V2 As Double
        # 'Dim item_name As String
        # 'Dim r As Range
        # If ActiveSheet Is Nothing Then
        #  Exit Sub
        # End If
        # Set r = ActiveSheet.UsedRange
        f =self.getDblOne(2, "E")
        item_name =self.getCellValue(2, "B")
        self.setCellValue(3, "P",item_name)
        row_num =self.getRowCount()
        i = 5
        while i<= row_num:
            print(i)
            mass = self.getDbl(i, "D")
            m2 = self.getDbl(i, "H")
            m1 = self.getDbl(i, "I")
            m0 = self.getDbl(i, "J")
            m3 = self.getDbl(i, "K")
            m4 = self.getDbl(i, "L")
            m5 = self.getDbl(i, "M")
            V1 = self.getDbl(i, "F")
            V2 = self.getDbl(i, "G")
            if mass == 0:
                pass
                print("pass")
            else:
                if V2 == 0:
                    V1 = 1
                    V2 = 1
                out = (m2 - m1 - m0 + m3 - m4 - m5) / mass * V1 / V2 * f * 100
                print(m2,m1,m0,m3,m4,m5,mass,V1,V2,f)
                print(out)
                self.setCellValue(i, "P",out)
            i+=1
        self.ax.setFocus()
        pass
    def onOpenWord(self):
        path, _ = QFileDialog.getOpenFileName(
            self, '请选择excel文件', '', 'excel(*.xlsx *.xls)')
        if not path:
            return
        # self.ax.querySubObject("Open(const QString&)", path);
        # 不显示窗体
        # self.axWidget.dynamicCall('SetVisible (bool Visible)', 'false')
        # self.axWidget.setProperty('DisplayAlerts', False)
        self.ax.setControl(path)
    def closeEvent(self,e):
        # self.ax.dynamicCall("Close()");
        self.ax.clear()
        # self.excel.dynamicCall('Quit()')
        print("close")

if __name__ == '__main__':
    import sys
    from PyQt5.QtWidgets import QApplication
    app = QApplication(sys.argv)
    w = Window()
    w.resize(1300,800)
    w.show()
    sys.exit(app.exec_())

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:/a/680279.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

JL-03-Y1 清易易站

产品概述 清易易站是清易电子新研发的一体式气象站&#xff0c;坚持科学化和人文化相结合的设计理念&#xff0c;应用新检测原理研发的传感器观测各类气象参数&#xff0c;采用社会上时尚的工艺理念设计气象站的整体结构&#xff0c;实现了快速观测、无线传输、数据准确、精度较…

案例 10kV能源站配电室电气设备集中监控系统

1 项目概况 青山节能科技10kV能源站项目是一个现代化的配电室&#xff0c;包括变压器、高压柜、低压柜等多台设备&#xff0c;为了提高运行效率和安全性&#xff0c;配电室电气设备集中监控系统接入了轨道巡检机器人、“SF6 & O2”双气体探测器、漏水探测器、无源无线电缆…

智慧校园建设经验分享

近年来&#xff0c;智慧校园建设在教育领域引起了广泛的关注和讨论。作为现代化教育的一部分&#xff0c;智慧校园为学生、教师和学校管理者提供了更加便捷、高效的教育环境。下面&#xff0c;我们将分享一些成功的智慧校园建设经验&#xff0c;希望对大家有所启发。 首先&…

【最新鸿蒙应用开发】——一篇搞懂什么是UIAbility

UIAbility组件 UIAbility组件是一种包含UI的应用组件&#xff0c;UIAbility组件是系统调度的基本单元&#xff08;最小单元&#xff09;&#xff0c;为应用提供绘制界面的窗口&#xff0c;主要用于和用户交互。一个应用可以包含一个或多个UIAbility组件。 UIAbility的设计理念…

LeetCode-103. 二叉树的锯齿形层序遍历【树 广度优先搜索 二叉树】

LeetCode-103. 二叉树的锯齿形层序遍历【树 广度优先搜索 二叉树】 题目描述&#xff1a;解题思路一&#xff1a;层序遍历&#xff0c;唯一区别就是ans.append(level[::-1] if len(ans) % 2 else level)背诵版&#xff1a;解题思路三&#xff1a;0 题目描述&#xff1a; 给你二…

【Redis数据库百万字详解】命令操作

文章目录 一、连接命令二、键命令 &#x1f308;你好呀&#xff01;我是 山顶风景独好 &#x1f388;欢迎踏入我的博客世界&#xff0c;能与您在此邂逅&#xff0c;真是缘分使然&#xff01;&#x1f60a; &#x1f338;愿您在此停留的每一刻&#xff0c;都沐浴在轻松愉悦的氛围…

工业楼控暖通组态恒温检测控制大屏前端UI案例

工业楼控暖通组态恒温检测控制大屏前端UI案例

详解MyBatis(三)

目录 1.#{} 和 ${} 1.1#{} 和${} 使用 Integer类型参数 String类型参数 1.2#{} 和 ${}区别 1.2.1#{}性能更高&#xff08;预编译&#xff09; 1.2.2#{}更安全&#xff08;防止SQL注入&#xff09; 1.3排序功能 1.4like查询 2.数据库连接池 2.1连接池介绍 2.2更换连接池…

从零入手人工智能(1)——卷积神经网络

1.前言 本人作为一名单片机工程师&#xff0c;近期对人工智能领域产生了浓厚的兴趣&#xff0c;并开始了我的探索之旅。人工智能是一个博大精深的领域&#xff0c;我相信有许多志同道合的朋友也希望涉足这个领域&#xff0c;因此我写下这篇文章&#xff0c;旨在详细记录我学习…

JavaSE——学习总结

一、初识Java 运行Java程序 Java是一门半编译型、半解释型语言 先通过javac编译程序把源文件进行编译&#xff0c;编译后生成的.class文件是由字节码组成的&#xff0c;和平台无关、面向JVM的文件&#xff0c;最后启动java虚拟机来运行.class文件&#xff0c;此时JVM会将字节…

CRT 安装过程出现许可证向导未成功完成

在下载使用SecureCRT和SecureFX时&#xff0c;SecureCRT按照教程很容易破解&#xff0c;而SecureFX使用补丁无法正常破解。 就是会出现了这个问题 The license wizard did not complete successfully. Possible errors include: -The license is for a different version of…

systemctlm-cosim-demo项目分析

概述 systemctlm-cosim-demo项目是Xilinx的systemc库的demo工程。 环境安装 qemu安装 cd xilinx_proj/Downloads git clone https://github.com/Xilinx/qemu.git cd qemu git checkout 74d70f8008# Configure and build # zynq7000 # ./configure --target-list"arm-s…

唯众智联网(AIoT)应用开发教学实训解决方案

一、引言 随着信息技术的飞速发展&#xff0c;物联网&#xff08;IoT&#xff09;和人工智能&#xff08;AI&#xff09;技术逐渐融合&#xff0c;形成了智联网&#xff08;AIoT&#xff09;这一新兴领域。智联网通过智能化设备、传感器、云计算等技术手段&#xff0c;实现了数…

[数据集][目标检测]道路圆石墩检测数据集VOC+YOLO格式461张1类别

数据集格式&#xff1a;Pascal VOC格式YOLO格式(不包含分割路径的txt文件&#xff0c;仅仅包含jpg图片以及对应的VOC格式xml文件和yolo格式txt文件) 图片数量(jpg文件个数)&#xff1a;462 标注数量(xml文件个数)&#xff1a;462 标注数量(txt文件个数)&#xff1a;462 标注类别…

懒人开发者的福音,轻松开发应用无需搭建服务!

近日&#xff0c;一款轰动开发圈的神器正以“太硬核了&#xff01;疯传开发圈&#xff01;”的口碑迅速走红&#xff0c;那就是Memfire Cloud&#xff01;这款一站式开发应用&#xff0c;不仅让懒人开发者尽享便利&#xff0c;更为开发者们带来了前所未有的开发体验。 对于懒人…

【IC验证】UVM实验lab01

1. 工厂的注册、创建和覆盖 1.1 注册 object组件使用宏uvm_obeject_ultis(string name)来创建&#xff0c;component组件使用uvm_object_ultis(string name, parent)来创建 class trans extends uvm_object;/*定义*/bit[31:0] data;uvm_object_ultis(trans)/*注册*/function …

工业无线wifi系统搭配高速路由,解决联网及数据传输

​面对日益复杂的工业应用场景,企业对无线网络的高速、可靠和安全提出了更高要求。星创易联SR600系列多网口4G路由器应运而生,为工业无线WiFi系统提供了一个性能卓越的高速路由方案。&#xff08;key-iot.com/iotlist/sr600-5.html&#xff09; SR600路由器集4G LTE、虚拟专用…

机器学习算法 —— 基于鸢尾花数据集的逻辑回归分类

&#x1f31f;欢迎来到 我的博客 —— 探索技术的无限可能&#xff01; &#x1f31f;博客的简介&#xff08;文章目录&#xff09; 目录 实践演示基于鸢尾花&#xff08;iris&#xff09;数据集的逻辑回归分类库函数导入数据读取/载入数据信息简单查看可视化展示利用逻辑回归模…

香橙派 Orange AIpro 测评记录视频硬件解码

香橙派 Orange AIpro 测评记录视频硬件解码 香橙派官网&#xff1a;http://www.orangepi.cn/ 收到了一块Orange Pi AIpro开发板&#xff0c;记录一下我的测评~测评简介如下&#xff1a;1.连接网络2.安装流媒体进行硬件解码测试3.安装IO测试 简介 Orange Pi AI Pro 是香橙派联合…

Python爬虫协程批量下载图片

import aiofiles import aiohttp import asyncio import requests from lxml import etree from aiohttp import TCPConnectorclass Spider:def __init__(self, value):# 起始urlself.start_url value# 下载单个图片staticmethodasync def download_one(url):name url[0].spl…