我正在使用 rpyc python 服务器来处理通过电子邮件发送的请求。我正在将它们加载到 Excel 吸墨纸中,其想法是在收到新请求后通过运行宏来自动更新 Excel。
但是,我无法初始化工作簿对象。下面的代码可以正常打开工作簿(startExcel),但是当我运行 RunThis 方法时,它会打印 0,因为工作簿中尚未初始化。
有什么想法可以解决这个问题吗?
from threading import Thread, Lock
import rpyc
from rpyc.utils.server import ThreadedServer
import win32com.client
from win32com.client import DispatchEx
import pythoncom
import os
import time
class MyService(rpyc.Service):
excelInitialized = False
xl = 0
wb = 0
def exposed_startExcel(self):
pythoncom.CoInitialize()
xl, wb = loadExcelEnv()
print wb
ws = wb.Sheets('RequestBlotter')
xl.Application.Run("ThisWorkbook.cleardata")
xl.Application.Run("ThisWorkbook.UpdateBlotter")
def exposed_RunThis(self):
print self.wb
def loadExcelEnv():
xl = DispatchEx('Excel.Application')
xl.DisplayAlerts = True
xl.Visible = True
wb = xl.Workbooks.Open(dir_path + '\\Repo Blotter.xlsm')
return xl, wb
server = ThreadedServer(MyService, port = 33445, protocol_config = {"allow_public_attrs" : True})
dir_path = os.path.dirname(os.path.realpath(__file__))
t = Thread(target = server.start)
t.daemon = True
t.start()
conn = rpyc.connect("localhost", 33445)
c = conn.root
c.startExcel()
while True:
time.sleep(10)
c.exposed_RunThis()