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.