【问题标题】:Open, Save, then Close Excel files in Python在 Python 中打开、保存和关闭 Excel 文件
【发布时间】:2021-11-24 01:34:24
【问题描述】:

我正在尝试遍历大约 300 个 xls 文件。目标是打开,保存,然后关闭每一个。到目前为止,我有以下内容:

files = glob.glob("C:/Users/cmoore/Excel Files/*.xls")

xl = win32com.client.DispatchEx("Excel.Application")
xl.DisplayAlerts = False

for wb in files:  
    xl.Workbooks.Open(wb)
xl.Visible = False
xl.Close(wb)
xl.Quit()

问题在于它不会循环遍历所有文件。通常有大约 5 个不被触及。然后在代码运行完成后出现以下错误:

"ret = self._oleobj_.InvokeTypes(1923, LCID, 1, (13, 0), ((8, 1), (12, 17), (12, 17), (12, 17), (12, 17), (12, 17), (12, 17), (12, 17), (12, 17), (12, 17), (12, 17), (12, 17), (12, 17), (12, 17), (12, 17)),Filename
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'Microsoft Excel', 'Open method of Workbooks class failed', 'xlmain11.chm', 0, -2146827284), None)"

有什么想法吗?

【问题讨论】:

    标签: python excel xlsx xls


    【解决方案1】:

    您在循环内部打开文件并在外部关闭它。对于 300 次打开,您只有一次关闭。尝试在循环内推近

    在循环内,关闭工作簿而不是 xl 对象。

    for wb in files:  
        xl.Workbooks.Open(wb)
        xl.Visible = False
        wb.Close(True)
    

    【讨论】:

    • 我现在收到以下错误: raise AttributeError("'%s' object has no attribute '%s'" % (repr(self), attr)) AttributeError: '' object has no attribute 'Close'
    • 试试这个 wb.Close(True)