Python Win32 COM错误-内部错误-缓冲区长度不是使用dataframe.torecords()时遇到的序列长度

Python Win32 COM错误-内部错误-缓冲区长度不是使用dataframe.torecords()时遇到的序列长度,python,pandas,win32com,Python,Pandas,Win32com,我正在使用以下代码使用win32com.client将现有数据框复制到excel工作表。下面是代码 import win32com.client as win32,sys import pandas as pd excel_application = win32.Dispatch("Excel.Application") excel_application.Visible = True lta_df = pd.read_excel("C:/Temp/tem

我正在使用以下代码使用win32com.client将现有数据框复制到excel工作表。下面是代码

    import win32com.client as win32,sys
    import pandas as pd
    excel_application = win32.Dispatch("Excel.Application")
    excel_application.Visible = True
    lta_df = pd.read_excel("C:/Temp/temp_lta.xlsx",sheetname=0,
                                    header=0,na_filter=False)
    lta_df["Updated"] = pd.to_datetime(lta_df["Updated"])
    workbook = excel_application.Workbooks.Open("C:/Temp/temp_lta.xlsx")
    ws= workbook.Sheets.Add(After=workbook.Sheets(workbook.Sheets.count))
    start_row= 1
    start_col = 5
    lta_df= lta_df.reset_index()

    ws.Range(ws.Cells(start_row,start_col),
     ws.Cells(start_row+len(lta_df.index)-1,start_col+len(lta_df.columns))
     ).Value =  lta_df.to_records(index=False)
当我使用_records()时,出现以下错误


出现错误是因为win32不理解您的数据类型(pd.Dataframe或np.ndarray)。我的做法是

# first by converting dataframe to contiguous array 
# this is needed because array has to be C_CONTIGUOUS in order to
# write it using win32com
# you can check whether your array is contiguous by using .flags method
lta_df2 = np.ascontiguousarray(lta_df) 
# second step is to convert the array to list
lta_df3 = lta_df2.tolist()

# now you can write lta_df3 to excel using win32com
start_row = 1
start_col = 1
ws.Range(ws.Cells(start_row,start_col),
 ws.Cells(start_row+len(lta_df.index)-1,start_col+len(lta_df.columns))
 ).Value = lta_df3 
另外,我建议您添加python和pandas标记

另外#2,您可能希望从
len(lta_df.columns)
中减去1,就像您对
start_row+len(lta_df.index)-1所做的那样

      start_row = 1
      start_col = 1
      arr_temp = lta_df.values.copy(order="C")
      ws.Range(ws.Cells(start_row,start_col),
     ws.Cells(start_row+len(lta_df.index)-1,start_col+len(lta_df.columns))
     ).Value = arr_temp
# first by converting dataframe to contiguous array 
# this is needed because array has to be C_CONTIGUOUS in order to
# write it using win32com
# you can check whether your array is contiguous by using .flags method
lta_df2 = np.ascontiguousarray(lta_df) 
# second step is to convert the array to list
lta_df3 = lta_df2.tolist()

# now you can write lta_df3 to excel using win32com
start_row = 1
start_col = 1
ws.Range(ws.Cells(start_row,start_col),
 ws.Cells(start_row+len(lta_df.index)-1,start_col+len(lta_df.columns))
 ).Value = lta_df3