我们每次用 Python 写入文件时是否都必须打开 excel 文件?

Do we have to open excel file EVERYTIME we write in it with Python?

我必须使用 Python 在 Excel 文件上书写。我用win32com做的。

我想打开它先做一些事情然后写入我的文件做更多的事情然后再写入文件。

但是如果我没有在每次写入前打开文件,我会收到此错误消息:

pywintypes.com_error: (-2146827864, 'OLE error 0x800a01a8', None, None)

这是我的代码:

connection = pypyodbc.connect('Driver={SQL Server};'
                'Server=SRVAKTCT-SQL\TCTSQL;'
                'Database=K;'
                'uid=Y;pwd=x')

cursor = connection.cursor()

for log, TA in zip(listeID,ListeTA):
    NomTA=TA[0]
    Equipe=TA[1]
    if log:

        #doing stuff
        results = something
        temps_log=results[0]
        print(temps_log)
        if temps_log is not None:
            temps_log=str(datetime.timedelta(seconds=int(temps_log)))

        excel = win32.gencache.EnsureDispatch('Excel.Application')
        wb = excel.Workbooks.Open('//Srvaktct-bur02/Copie de vide.xlsx')
        ws=wb.Worksheets(date_onglet)
        ws.Cells(ligne_cumul,10).Value=temps_log
        #wb.Close(True)
    #wb = excel.Workbooks.Open('//Srvaktct-bur02/Copie de vide.xlsx')
    #ws=wb.Worksheets(date_onglet)
    ws.Cells(ligne_cumul,2).Value=NomTA
    ws.Cells(ligne_cumul,3).Value=Equipe

    wb.Close(True)
    excel.Application.Quit()
    ligne_cumul += 1

这里的代码只有在我取消评论区的评论时才有效。

因为每次循环迭代都会打开文件。

你应该移动行

excel = win32.gencache.EnsureDispatch('Excel.Application')
wb = excel.Workbooks.Open('//Srvaktct-bur02/Copie de vide.xlsx')
ws = wb.Worksheets(date_onglet)

到循环之前,因此您不需要在每次迭代中关闭并重新打开文件。

if I don't open the file everytime before writing, i have this error message:

嗯,是的,因为如果您没有要写入 的文件对象,您还希望发生什么?

您正在循环中执行 wb.Close() 调用,因此,因为您关闭了它,所以如果您想再次写入(或读取)它,则还必须重新打开它。您在循环中两次 closing/opening 文件,并且还在循环内执行 excel.Quit 操作,这要求您在每次交互时重新实例化它更好的方法是实例化 excel 在循环之外(后来 Quit 它在循环终止后)。

未经测试,但看看它是否有帮助(已修改,因为你提到它是同一个文件

connection = pypyodbc.connect('Driver={SQL Server};'
                'Server=SRVAKTCT-SQL\TCTSQL;'
                'Database=K;'
                'uid=Y;pwd=x')

cursor = connection.cursor()
wb, ws = None, None
filePath = '//Srvaktct-bur02/Copie de vide.xlsx'
# Get a handle on Excel application:
excel = win32.gencache.EnsureDispatch('Excel.Application')
# Open the file outside of the loop, too:
wb = excel.Workbooks.Open(filePath)
ws=wb.Worksheets(date_onglet)
for log, TA in zip(listeID,ListeTA):
    NomTA=TA[0]
    Equipe=TA[1]
    if log:
        #doing stuff
        results = something
        temps_log=results[0]
        print(temps_log)
        if temps_log is not None:
            temps_log=str(datetime.timedelta(seconds=int(temps_log)))
            ws.Cells(ligne_cumul,10).Value=temps_log
    ws.Cells(ligne_cumul,2).Value=NomTA
    ws.Cells(ligne_cumul,3).Value=Equipe
    ligne_cumul += 1
# Don't close wb or Quit Excel inside the loop!
wb.Close(True)
excel.Application.Quit()