我怎么能插入一个数据框在Excel中使用xlwings没有pywintypes.com_error?

我正在使用Excel和xlwings。 我有一个book.xlsm,在第一个表单上有一个button分配给以下vba代码:

book.xlsm!ThisWorkbook.get_data 

在VBA上,我添加了这个button被调用并执行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行。 使用更less的数据运行没有错误。

更新:目前没有解决scheme,但有一个解决方法提供的意见: 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"([az]+)([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问题页面上发布了一个解决方法function。 它将DataFrame分成更小的块并将它们插入到Excel中。 不幸的是,正如你已经注意到的那样,这个函数被窃听,导致块之间出现空行。

我修改了function,现在它的工作完美。

 # 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"([az]+)([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的块大小是好的,但是你可以根据你的需要来改变它。

对不起,复活一个旧的线程。

当我运行上述函数作为来自另一个函数的调用时,我得到了各种各样的错误,主要围绕Range项目。 是否有可能“独立”写这个函数,使其包含import和target? 我有:

 def dump_largeDF(wb, df, sheetName, startcell, chunk_size): import pandas as pd import xlwings as xw import re if len(df) <= (chunk_size + 1): wb.sheets(sheetName).Range(startcell, index=False, header=False).value = df else: # Chunk df and and dump each c = re.match(r"([az]+)([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)): wb.sheets(sheetName).Range(row + str(col), index=False, header=False).value = chunk col += chunk_size