I want to print out the whole data frame into an excel workbook using win32com.client.
It works fine with single values or arrays, however when I try to copy and paste the whole data frame with dimension x * y, it has errors like:
TypeError: Objects for SAFEARRAYS must be sequences (of sequences), or a buffer object.
I'm wondering if there is a way to output the data frame. Thanks in advance.
My code that arises that error above:
sel = ws.Range('B11:O72')
sel.Value = db[:]
I'm doing this because printing one by one is quite slow.
Hope this can help answer your question:
import pandas as pd
import numpy as np
import win32com.client as MyWinCOM
# Book2.xlsx must already be open
xl = MyWinCOM.GetObject(None, "Excel.Application")
wb = xl.Workbooks("Book2.xlsx")
ws = wb.Worksheets("Sheet1")
d = {'time' : pd.Series([1., 2., 3., 4.], index=['a', 'b', 'c', 'd']),
'legnth' : pd.Series([4., 5., 6., 7.], index=['a', 'b', 'c', 'd'])}
df = pd.DataFrame(d)
StartRow = 1
StartCol = 1
ws.Range(ws.Cells(StartRow,StartCol),# Cell to start the "paste"
ws.Cells(StartRow+len(df.index)-1,
StartCol+len(df.columns)-1)
).Value = df.values
# OR
StartRow = 1
StartCol = 5
ws.Range(ws.Cells(StartRow,StartCol),# Cell to start the "paste"
ws.Cells(StartRow+len(df.index)-1,
StartCol+len(df.columns))# No -1 for the index
).Value = df.to_records()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.