0

Here's the code I am using

excel = win32com.client.Dispatch('Excel.Application')
wb = excel.Workbooks.Open('myWorkbook.xlsx')
df = pd.DataFrame({'A':[1,2,3,4,5], 'B':[11,22,33,44,55], 'C':['a','b','c','d','e']})
wb.Sheets('Template').Copy(Before=None, After=wb.Sheets(wb.Sheets.count))

ws = wb.Sheets(wb.Sheets.count)
ws.Range(ws.cells(40,19), 40+len(df.index)-1, 19+len(df.columns)).Value = df.values

But I always receive the following error: ValueError: ndarray is not C-contiguous

Aroosh Rana
  • 112
  • 11
  • Why would you do this with COM? pandas writes to excel natively – user1558604 May 12 '20 at 03:29
  • @user1558604 Yes, but the actual code is in a loop. In that it is copying multiple dataframes. But to me it gives the ValueError, I cant understand why. – Aroosh Rana May 12 '20 at 03:37
  • I'm not sure how being in a loop affects the fact that pandas can write to excel itself without COM. I can't help with excel COM because honestly I can't think of any reason to do it that way. If you post the full error and trace others may be able to help. – user1558604 May 12 '20 at 03:43
  • In python, openpyxl is possibly the most commonly used library to interact with excel, and pandas can also write to excel. for interactive use pandas can also put the data frame contents in a clipboard that you can paste where appropriate. I think you will find more support if you were using a more commonly used tool – Haleemur Ali May 12 '20 at 03:51
  • https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_excel.html – r.ook May 12 '20 at 04:02
  • Hi @r.ook, I tried with that but as I said I am writing different dfs to sheet, so when i write another the previous df values gets cleared – Aroosh Rana May 12 '20 at 13:51
  • It might be worthwhile to concat your dataframes per sheet and write to excel, provided they are the same structure. As others said using COM could be quite error prone when an alternative exists. The best I can think of would be to utilize the `pd.DataFrame.to_clipboard()` method and then paste it with COM, but it's awfully manual. – r.ook May 12 '20 at 15:45

0 Answers0