临时pywin32使用

pywin32 · PyPI  https://pypi.org/project/pywin32/


        import time
        from win32com.client import Dispatch
        my_file_path=QtWidgets.QFileDialog.getOpenFileName(self, "打开打印模板", "/", "*.xls;*.xlsx;*.csv")
        print(my_file_path)
        xl=Dispatch("Excel.Application")
        xl.Visible=1
        my_excel_wb=xl.Workbooks.open(my_file_path)
        time.sleep(3)
        ws = my_excel_wb.Worksheets(1)

('D:/干部.xlsx', '*.xlsx')

(一)错误提示:

Exception "unhandled pywintypes.com_error"
(-2147352567, '发生意外。', (0, 'Microsoft Excel', '抱歉,无法找到 *.xlsx。是否可能被移动、重命名或删除?', 'xlmain11.chm', 0, -2146827284), None)
File: d:\ProgramData\Anaconda3\lib\site-packages\win32com\client\dynamic.py, Line: 2

(二)解决方法(已验证对了):

 my_file_path=QtWidgets.QFileDialog.getOpenFileName(self, "打开打印模板", "/", "*.xls;*.xlsx;*.csv")

my_file_path其实是一个元组tuple数据类型,在打开文件对话框中,选中12这个EXCEL文件,返回结果:('D:/12.xlsx', '*.xls;*.xlsx;*.csv')。

my_excel_wb=xl.Workbooks.open(my_file_path),变为

my_excel_wb=xl.Workbooks.open(my_file_path[0])  #选中元组的第一个值,即文件路径,就正常了。

网上解决方法:

原因:当前程序没有对目标文件的支配权限。挂载的WPS并没有权限去另存为这个被打开的文档。之前打开的尚未被关闭。
当文件读写速度较快的时候,上一个Excel未关闭,下一个就打开,导致出现以上问题。
time.sleep(3)解决!

python - Why is the information for pywintypes.com_error unreadable? - Stack Overflow  https://stackoverflow.com/questions/7544587/why-is-the-information-for-pywintypes-com-error-unreadable

pywintypes.com_error in Python during Excel import - Stack Overflow  https://stackoverflow.com/questions/24320397/pywintypes-com-error-in-python-during-excel-import

The error occurred because the sheet I wanted to call from the excel workbook did not match the name I was referencing it by in my python code. My sheet was actually Sheet1 (by default in excel) but I was calling a sheet Input1 as seen in line 5 of my module gasprop. The mismatch in names caused this error.




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值