我正在尝试使用网络应用程序 Flask/Python 在 excel 中启动一个宏,当用户按下按钮时,后面的进程将打开一个 excel 执行一个宏并返回结果。
如果我使用 IDE Visual Studio 2015 执行此操作,则没有问题,并且过程运行良好,当我尝试使用 IIS(发布)时,我可以导航到 Web 应用程序,但是当我按下按钮时,会出现此错误:
Error occurred:
Traceback (most recent call last):
File "C:\inetpub\wwwroot\MyWebSite\wfastcgi.py", line 736, in main
result = handler(record.params, response.start)
File "C:\Anaconda2\lib\site-packages\flask\app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Anaconda2\lib\site-packages\flask\app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "C:\Anaconda2\lib\site-packages\flask\app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "C:\Anaconda2\lib\site-packages\flask\app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "C:\Anaconda2\lib\site-packages\flask\app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Anaconda2\lib\site-packages\flask\app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Anaconda2\lib\site-packages\flask\app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Anaconda2\lib\site-packages\flask\app.py", line 1461, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File ".\QPX_Test\upload.py", line 62, in upload
process_excel.up_route(variable_forsave, 'C:\Tool_OP14\System\Main System FIndx', 'System','B1')
File ".\QPX_Test\process_excel.py", line 27, in up_route
xlApp = win32com.client.Dispatch('Excel.Application')
File "C:\Anaconda2\lib\site-packages\win32com\client\__init__.py", line 95, in Dispatch
dispatch, userName = dynamic._GetGoodDispatchAndUserName(dispatch,userName,clsctx)
File "C:\Anaconda2\lib\site-packages\win32com\client\dynamic.py", line 114, in _GetGoodDispatchAndUserName
return (_GetGoodDispatch(IDispatch, clsctx), userName)
File "C:\Anaconda2\lib\site-packages\win32com\client\dynamic.py", line 91, in _GetGoodDispatch
IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx, pythoncom.IID_IDispatch)
com_error: (-2147024891, 'Access is denied.', None, None)
StdOut:
StdErr:
我尝试了一切:
安全文件夹 ( C:\inetpub\wwwroot) 我添加了具有完全权限的 IUSR 用户,与 PCNAME\IIS_IUSRS 和我的 Web 应用程序(应用程序池身份)相同。
在 Microsoft Excel 的 DCOMcnfg 上,我在启动和激活权限上设置了自定义选项并将权限添加到:
- 国际标准化组织
- IIS_IUSRS
- 我的网站(网络应用程序)
这是代码的一部分,但是是最重要的部分:
所以这是用 jade 编写的开始 Python 代码的部分:
.container-fluid
.row
.grid-12
.jumbotron
h1 Test Tool
p Testing for web application development
.row
.section.group
.col.span_2_of_3
h1 Step 1
p For select the Input Data File, please press the "Select Data Input" button
form(action='upload', method='post', enctype='multipart/form-data')
.table
input.filestyle(type='file', name = 'file', data-buttonname='btn-primary', data-buttonText= 'Select Data File', data-iconName= 'fa fa-database', data-buttonBefore='true', data-placeholder = 'No File')
.table
span.btn.btn-primary.btn-file
| Upload
span.fa.fa-cloud-upload.fa-1x.pull-left
input(type='submit')
所以当用户按下按钮时,选择的文件被上传,但首先 Python 代码调用另一个例程打开 excel 并做一些事情
import os
from QPX_Test import app
from flask import Flask, render_template, request, redirect, url_for, send_from_directory, after_this_request
from werkzeug import secure_filename
from win32com.client import Dispatch
import pythoncom
import process_excel
main_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'Server')
# Initialize the Flask application
# app = Flask(__name__)
# This is the path to the upload directory
app.config['UPLOAD_FOLDER'] = main_path
# These are the extension that we are accepting to be uploaded
app.config['ALLOWED_EXTENSIONS'] = set(['xls', 'xlsm','xlsx'])
# For a given file, return whether it's an allowed type or not
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1] in app.config['ALLOWED_EXTENSIONS']
# This route will show a form to perform an AJAX request
# jQuery is loaded to execute the request and update the
# value of the operation
@app.route('/up')
def index():
return render_template('upload.jade')
# Route that will process the file upload
@app.route('/upload', methods=['POST'])
def upload():
# Get the name of the uploaded file
file = request.files['file']
# Check if the file is one of the allowed types/extensions
if file and allowed_file(file.filename):
# Make the filename safe, remove unsupported chars
filename = secure_filename(file.filename)
# Move the file form the temporal folder to
# the upload folder we setup
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
# Redirect the user to the uploaded_file route, which
# will basicaly show on the browser the uploaded file
#return redirect(url_for('uploaded_file',
# filename=filename))
variable_forsave = os.path.join(main_path, filename)
filename_save= os.path.join(main_path, 'Test.xlsm')
# Select Excel File and Save Route into System
process_excel.up_route(variable_forsave, 'C:\inetpub\wwwroot\MyWebSite\Tool\Main System', 'System','B1')
return render_template('webtools_petro.jade')
# after save the file do something
# This route is expecting a parameter containing the name
# of a file. Then it will locate that file on the upload
# directory and show it on the browser, so if the user uploads
# an image, that image is going to be show after the upload
#@app.route('/static/uploads/<filename>')
#def uploaded_file(filename):
# return send_from_directory(app.config['UPLOAD_FOLDER'],
# filename)
最后打开例程并做一些事情
import os
import win32com.client
from QPX_Test import app
from flask import Flask, render_template, request, redirect, url_for, send_from_directory, after_this_request
from werkzeug import secure_filename
from win32com.client import Dispatch
import pythoncom
import upload
from flask import send_file
import StringIO
pythoncom.OleInitialize()
def up_route(variabletosave, forsave, sheetsave, rangesave):
pythoncom.CoInitialize ()
xlApp = win32com.client.Dispatch('Excel.Application')
xlWb = xlApp.Workbooks.Open(forsave)
xlSht = xlWb.WorkSheets(sheetsave)
xlSht.Range(rangesave).value= variabletosave
xlApp.visible = True
xlWb.Saved = 0
xlWb.Save()
xlWb.Close(SaveChanges=True)
xlApp.application.Quit()
所以我认为当Python尝试打开excel但没有权限时会出现问题,有办法带来Python权限吗?
在此编辑---------------------------------------- ------------------------
好的,所以我创建了一个仅用于测试的新应用程序...
'索引
extends layout
block content
.jumbotron
h1 Excel Test
p.lead Testing the Privileges Features
p Current directory {{ testfile }}
form(action='test', method='post', enctype='multipart/form-data')
button(type="submit)
很简单
和 views.py
import os, sys
from datetime import datetime
from flask import render_template
from flask import request
from Test_Excel_Python import app
from Test_Excel_Python import Excel_test
import win32com.client
from werkzeug import secure_filename
from win32com.client import Dispatch
import pythoncom
import StringIO
app.debug = True
Folder_File= os.path.dirname(os.path.abspath(sys.argv[0]))
Folder_Excel_Files='Test_Excel_Python\Excel Files'
File_open = 'Test File'
File_Suffix= 'xlsx'
Real_Excel_Route= os.path.join(Folder_File, Folder_Excel_Files, File_open + "." + File_Suffix)
@app.route('/')
@app.route('/home')
def home():
"""Renders the home page."""
return render_template(
'index.jade',
title='Home Page',
year=datetime.now().year, testfile=Real_Excel_Route
)
@app.route('/test', methods=['POST'])
def test():
#Excel_test.Excel_Open #'esto es un test', Real_Excel_Route, 'Prueba','A1')
pythoncom.CoInitialize ()
xlApp = win32com.client.Dispatch('Excel.Application')
xlWb = xlApp.Workbooks.Open('C:\inetpub\wwwroot\MyTestExcel\Test_Excel_Python\Excel Files\Test File.xlsx')
xlSht = xlWb.WorkSheets('Sheet1')
xlSht.Range('A1').value= 'Testing Write here'
xlApp.visible = True
xlWb.Saved = 0
xlWb.Save()
xlWb.Close(SaveChanges=True)
xlApp.application.Quit()
return render_template('index.jade')
而且网络配置非常简单
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<handlers>
<add name="FlaskHandler" path="*" verb="*" modules="FastCgiModule" scriptProcessor="C:\Anaconda2\python.exe|C:\inetpub\wwwroot\MyTestExcel\wfastcgi.py" resourceType="Unspecified" />
</handlers>
<rewrite>
</rewrite>
</system.webServer>
</configuration>
与第一个程序一样,此例程在 Visual Studio 2015 上运行良好(启动)并访问 Localhost:5000
但是当我尝试使用 IIS localhost:82 时出现此错误:
Error occurred:
Traceback (most recent call last):
File "C:\inetpub\wwwroot\MyTestExcel\wfastcgi.py", line 736, in main
result = handler(record.params, response.start)
File "C:\Anaconda2\lib\site-packages\flask\app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Anaconda2\lib\site-packages\flask\app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "C:\Anaconda2\lib\site-packages\flask\app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "C:\Anaconda2\lib\site-packages\flask\app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "C:\Anaconda2\lib\site-packages\flask\app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Anaconda2\lib\site-packages\flask\app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Anaconda2\lib\site-packages\flask\app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Anaconda2\lib\site-packages\flask\app.py", line 1461, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File ".\Test_Excel_Python\views.py", line 64, in test
xlWb = xlApp.Workbooks.Open('C:\inetpub\wwwroot\MyTestExcel\Test_Excel_Python\Excel Files\Test File.xlsx')
File "<COMObject <unknown>>", line 8, in Open
com_error: (-2147352567, 'Exception occurred.', (0, u'Microsoft Excel', u"Microsoft Excel cannot access the file 'C:\\inetpub\\wwwroot\\MyTestExcel\\Test_Excel_Python\\Excel Files\\Test File.xlsx'. There are several possible reasons:\n\n\u2022 The file name or path does not exist.\n\u2022 The file is being used by another program.\n\u2022 The workbook you are trying to save has the same name as a currently open workbook.", u'xlmain11.chm', 0, -2146827284), None)
StdOut:
StdErr:
我已经尝试添加“xlApp.Interactive = False”,但问题仍然存在,我只更改了本地的应用程序标识以进行测试,当然,最后一次更改“访问被拒绝”问题消失了。
我给APPTOOL\appname添加了对security文件夹的读/写访问权限。
请帮忙,这太令人沮丧了!! :(
最佳答案
找到解决方案!!!,f**** bug arrrggggg 我很高兴/生气:
The solution for this appalling BUG in Microsoft IIS & Excel is terrific:
Create directory "C:\Windows\SysWOW64\config\systemprofile\Desktop " (for 64 bit Windows) or "C:\Windows\System32\config\systemprofile\Desktop " (for 32 bit Windows)
Set Full control permissions for directory Desktop (for example in Win7 & IIS 7 & DefaultAppPool set permissions for user
"IIS AppPool\DefaultAppPool")
微软到底是怎么回事!!!! 2010 年解决方案!!
关于python - 错误 Python - 214702489 访问被拒绝 (COM) 已更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34613298/