在Python中使用win32com将数据帧写入工作表

2024-09-30 12:22:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用win32把整个数据框打印成excel工作簿com.客户端. 在

它可以很好地处理单个值或数组,但是当我试图复制和粘贴维度为x*y的整个数据帧时,它会出现如下错误:

TypeError: Objects for SAFEARRAYS must be sequences (of sequences), or a buffer object.

我想知道有没有办法输出数据帧。提前谢谢。在

出现上述错误的代码:

^{pr2}$

我这样做是因为一个接一个地打印很慢。在


Tags: 数据com客户端forobjects粘贴错误数组
1条回答
网友
1楼 · 发布于 2024-09-30 12:22:25

希望这有助于回答您的问题:

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()

相关问题 更多 >

    热门问题