[英]copy entire excel worksheet to a new worksheet using Python win32com
[英]Write a data frame to worksheet using win32com in Python
我想使用win32com.client将整个数据框打印到excel工作簿中。
它适用于单个值或数组,但是当我尝试复制和粘贴维度为x * y的整个数据框时,它会出现以下错误:
TypeError: Objects for SAFEARRAYS must be sequences (of sequences), or a buffer object.
我想知道是否有一种方法来输出数据帧。 提前致谢。
我的代码出现上述错误:
sel = ws.Range('B11:O72')
sel.Value = db[:]
我这样做是因为一张一张地打印很慢。
希望这可以帮助回答您的问题:
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.