gpt4 book ai didi

python - 如何在没有 pywintypes.com_error 的情况下使用 xlwings 在 Excel 中插入数据框?

转载 作者:太空宇宙 更新时间:2023-11-04 03:39:28 36 4
gpt4 key购买 nike

我正在使用 Excel 和 xlwings。我有一个 book.xlsm,在第一张纸上有一个分配给以下 vba 代码的按钮:

book.xlsm!ThisWorkbook.get_data

在 VBA 上,我添加了这个,当调用按钮并执行 vba 代码时,它会运行:

Sub get_data()
RunPython ("import my_script; my_script.get_data()")
End Sub

my_script 如下:

import pandas as pd
from xlwings import Workbook, Range

def get_data():
wb = Workbook.caller()

df = pd.read_csv("data.csv")
Range("Sheet2", "A1").value = df

我遇到的问题如下:

pywintypes.com_error: (-2147024882, 'Not enough storage is available to complete this operation.', None, None)

data.csv文件有150000行,120行。它使用更少的数据运行而没有错误。

更新:目前没有解决方案,但评论中提供了解决方法:https://github.com/ZoomerAnalytics/xlwings/issues/77

我使用以下内容:

df = pd.read_csv(csv_file, na_values={"", " ", "-"})
df.fillna("-", inplace=True)
startcell = 'A1'
chunk_size = 2500
if len(df) <= (chunk_size + 1):
Range(sheet_name, startcell, index=False).value = df
else: # chunk df and and dump each (default is 10k)\n",
c = re.match(r"([a-z]+)([0-9]+)", startcell, re.I)
cL = c.group(1)
cN = int(c.group(2))
n = 0
for i in (df[rw:rw + chunk_size] for rw in xrange(0, len(df), chunk_size)):
if n == 0:
Range(sheet_name, cL + str(cN+n), index=False).value = i
cN += chunk_size
else:
Range(sheet_name, cL + str(cN+n)).value = i.values
cN += chunk_size
n += 1

我遇到的问题是,当我在工作表中插入数据时,在 5002 处有一个空行,在 7503、10004 处又出现了一个空行……我意识到我的代码中有一个错误,但我找不到它。

最佳答案

GitHub issue page 上发布了一个解决方法函数.它将 DataFrame 分成更小的 block 并将它们插入到 Excel 中。不幸的是,正如您所注意到的,该函数存在错误并导致 block ​​之间出现空行。

我修改了函数,现在它运行良好。

# Dumps a large DataFrame in Excel via xlwings.
# Does not include headers.
def dump_largeDF(df, startcell='A1', chunk_size=100000):
if len(df) <= (chunk_size + 1):
Range(startcell, index=False, header=False).value = df
else: # Chunk df and and dump each
c = re.match(r"([a-z]+)([0-9]+)", startcell, re.I) # A1
row = c.group(1) # A
col = int(c.group(2)) # 1
for chunk in (df[rw:rw + chunk_size] for rw in
range(0, len(df), chunk_size)):
print("Dumping chunk in %s%s" %(row, col))
Range(row + str(col), index=False, header=False).value = chunk
col += chunk_size

对我来说,100k 的 block 大小就可以了,但是您可以根据需要更改它。

关于python - 如何在没有 pywintypes.com_error 的情况下使用 xlwings 在 Excel 中插入数据框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27212643/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com