lsh*_*eng 0 python win32com dataframe
我想使用 win32com.client 将整个数据框打印到 excel 工作簿中。
它适用于单个值或数组,但是当我尝试复制和粘贴维度为 x * y 的整个数据框时,它会出现如下错误:
TypeError: Objects for SAFEARRAYS must be sequences (of sequences), or a buffer object.
Run Code Online (Sandbox Code Playgroud)
我想知道是否有办法输出数据帧。提前致谢。
我的代码出现上述错误:
sel = ws.Range('B11:O72')
sel.Value = db[:]
Run Code Online (Sandbox Code Playgroud)
我这样做是因为一张一张打印很慢。
希望这可以帮助回答您的问题:
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()
Run Code Online (Sandbox Code Playgroud)