【问题标题】:(-2147024891, 'Access is denied.', None, None)(-2147024891,\'访问被拒绝。\',无,无)
【发布时间】:2022-12-01 11:13:38
【问题描述】:

我正在开发 Django (v 3.2.6) 应用程序 (Python 3.9.1.),它需要使用 pywin32.com 写入 Excel 文件。

在客户端,它工作正常,但是当我在 Windows 11 服务器上使用 IIS (v 10) 投入生产时,出现上述错误。

我有一个读取用户输入的文件并写入项目目录的例程:

    if request.method == 'POST':
        
        # Create a form instance and populate it with the file from the request (binding):
        form = Name1_uploadForm(request.POST, request.FILES)
        if form.is_valid():
            # Create variable for uploaded file 
            uploaded_excel_file = form.cleaned_data['excel_file']
            # Write it to BASE_DIR
            with open(os.path.join(settings.BASE_DIR, form.cleaned_data['excel_file'].name), 'wb+') as destination:

                for chunk in uploaded_excel_file.chunks():
                    destination.write(chunk)
            # Allow the write process to conclude
            time.sleep(12)
            # Close the file
            destination.close()            
            # Call conversion function
            Name1_extraction(os.path.join(settings.BASE_DIR, form.cleaned_data['excel_file'].name))
            # redirect to a new URL:
            return HttpResponseRedirect(reverse('index') )
        else:
            form = Name1_uploadForm()

这会调用另一个函数(如下)来打开同一个文件:

def Name1_extraction(uploaded_excel_file):

    const = win32.constants

    # Need to run CoInitialize to use win32com.client
    pythoncom.CoInitialize()

    # Open Name1 excel with Win32com 
    excelFile = win32.gencache.EnsureDispatch('Excel.Application')

完整的错误如下:

enter image description here

enter image description here enter image description here

执行以下代码行时会发生错误:

excelFile = win32.gencache.EnsureDispatch('Excel.Application')

应用程序池是 IIS AppPool\DefaultAppPool。

DefaultAppPool 已被授予对文件夹 C:\Windows\SysWOW64\config\systemprofile\Desktop 和 C:\Windows\System32\config\systemprofile\Desktop 的完全访问权限

通过这些操作,我不希望看到任何错误

感谢您提供的任何帮助。

【问题讨论】:

  • 不支持服务器端 Office 自动化(IIS 上 Web 应用程序中的 Office COM 互操作),所以不要浪费任何人的时间。

标签: python-3.x django excel iis pywin32


【解决方案1】:

Microsoft 不推荐也不支持 Office 的服务器端自动化,Microsoft 强烈建议开发人员在需要开发服务器端解决方案时寻找 Office 自动化的替代方案。

由于Office设计的局限性,仅更改Office配置不足以解决所有问题。 Microsoft 强烈推荐一些不需要在服务器端安装 Office 并且可以比 Automation 更高效、更快地执行大多数常见任务的替代方案。

大多数服务器端自动化任务都涉及文档创建或编辑。 Office 2007 支持新的 Open XML 文件格式,允许开发人员在服务器端创建、编辑、读取和转换文件内容。这是处理来自服务的 Office 文件更改的推荐和支持方法。

Open XML SDK 2.5 for Office的使用方法,请参考微软文档:

https://learn.microsoft.com/en-us/office/open-xml/open-xml-sdk

Office服务器端自动化的注意事项,请参考这篇微软博客:

https://support.microsoft.com/en-us/topic/considerations-for-server-side-automation-of-office-48bcfe93-8a89-47f1-0bce-017433ad79e2

【讨论】:

    猜你喜欢
    • 2017-10-05
    • 2020-01-05
    • 2021-02-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    • 2012-01-01
    • 2012-01-22
    • 1970-01-01
    相关资源
    最近更新 更多