1

我目前正在尝试运行以下代码,但我不断收到错误消息

pywintypes.com_error: (-2147417842, '应用程序调用了为不同线程编组的接口。', 无, 无)

我是否需要通过单独的线程执行烧瓶功能。有没有其他方法可以创建一个全局 excel 实例并使用它来打开和修改单独的工作簿?

任何有关相同的帮助将不胜感激。

from flask import Flask, request, jsonify
import json   
import pythoncom
import win32com.client
from win32com.client import Dispatch

xl = None
xl = win32com.client.Dispatch("Excel.Application")

app = Flask(__name__)


@app.route("/check", methods=['POST'])
def check():

    pythoncom.CoInitialize()
    if request.method == 'POST':
        data = request.get_json()
        fname = data['fname']
        phName = data['PH_Name']
        liName = data['LI_NAME']
        ppm = data['PPM']
        policyTerm = data['Policy_Term']
        sumAssured = data['Sum_Assured']


        wb = None

        if xl : 
            wb = xl.Workbooks.Open(fname) 


            inp_sheet = wb.Sheets["Inputs"]

            #read data from sheet
            data = inp_sheet.Range('D8').Value


            wb.Close(False)
            xl.Quit()
            return (data)


if __name__ == '__main__':
    app.run(threaded=True, port=5001, debug=True)
4

1 回答 1

0

您应该尝试win32com在多线程后创建变量。

尝试这个:

from flask import Flask, request, jsonify
import json   
import pythoncom
import win32com.client
from win32com.client import Dispatch

xl = None

app = Flask(__name__)

@app.route("/check", methods=['POST'])
def check():

    pythoncom.CoInitialize()
    xl = win32com.client.Dispatch("Excel.Application")
    if request.method == 'POST':
        data = request.get_json()
        fname = data['fname']
        phName = data['PH_Name']
        liName = data['LI_NAME']
        ppm = data['PPM']
        policyTerm = data['Policy_Term']
        sumAssured = data['Sum_Assured']


        wb = None

        if xl : 
            wb = xl.Workbooks.Open(fname) 


            inp_sheet = wb.Sheets["Inputs"]

            #read data from sheet
            data = inp_sheet.Range('D8').Value


            wb.Close(False)
            xl.Quit()
            return (data)


if __name__ == '__main__':
    app.run(threaded=True, port=5001, debug=True)
于 2021-05-06T15:35:33.823 回答