我们是否必须打开excel文件,每次我们用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 

这里的代码只有在我注销注释区域时才起作用。

如果在写入之前每次都不打开文件,我有这个错误消息:

那么是的,因为如果你没有文件对象来写,你还会期望发生什么?

你正在循环中做一个wb.Close()调用,所以,因为你closures了它,所以如果你想再次写入(或读取它),你也必须重新打开它。 你在循环中closures/打开两个文件,你也在做循环内的excel.Quit操作,这需要你在每个excel.Quit重新实例化。更好的方法是在循环之外实例化excel (之后在循环结束后Quit )。

未经testing,但看看是否会有所帮助( 修改,因为你提到它是相同的文件

 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() 

因为您在循环的每个迭代中都打开文件。

你应该移动线

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

到循环之前,所以您不必在每次迭代中closures并重新打开文件。