python - 如何使用 pandas 写入 Excel 文档的中间

标签 python excel pandas

我有一个 Excel 文档(包含格式和所有内容),前几行是标题和页眉内容。

在第 11 行,我从实际数据、列标题和所有内容开始。

我正在计算要放入此表中的数据。

我可以使用 header=[11] 读取数据,并且它将使用正确的列名称、索引和所有内容读入。我可以填写数据、根据需要添加列等。

当我尝试保存文件时出现问题。如果我只是使用 to_excel 保存,它会保存,但没有任何标题内容或原始格式。

如何将数据框插入现有 Excel 文档中的某个位置?

预计到达时间:

我忘记提及的一件事可能很重要,那就是原始 Excel 文件在整个数据部分也具有条件格式。我想保持这一点。

ETA2:添加 Josh 评论的详细信息。

In [153]: xl.to_excel(writer,  "Program Area Summary.xls", startrow=11)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-153-6541427c4a61> in <module>()
----> 1 xl.to_excel(writer,  "Program Area Summary.xls", startrow=11)

/Users/brianp/work/cyan/venv/lib/python2.7/site-packages/pandas/core/frame.pyc in to_excel(self, excel_writer, sheet_name, na_rep, float_format, columns, header, index, index_label, startrow, startcol, engine, merge_cells, encoding, inf_rep, verbose)
   1422         formatted_cells = formatter.get_formatted_cells()
   1423         excel_writer.write_cells(formatted_cells, sheet_name,
-> 1424                                  startrow=startrow, startcol=startcol)
   1425         if need_save:
   1426             excel_writer.save()

/Users/brianp/work/cyan/venv/lib/python2.7/site-packages/pandas/io/excel.pyc in write_cells(self, cells, sheet_name, startrow, startcol)
   1243             wks = self.book.create_sheet()
   1244             wks.title = sheet_name
-> 1245             self.sheets[sheet_name] = wks
   1246 
   1247         for cell in cells:

TypeError: list indices must be integers, not str

我是在 ipython 中完成此操作的,因此没有太多其他代码。 xl 是一个数据框。

最佳答案

我知道有两个选项,第一个是我通过搜索 StackOverflow 找到的,你可以找到 here 。您可以使用该示例以及 to_excel 中的 startrow 参数。方法在第 11 行或其他所需位置启动 DataFrame。喜欢

df.to_excel(writer, startrow=11, startcol=2).

第二个选项是 xlwings库,这是我在 Python 中使用 Excel 时通常使用的库。 Here是 xlwings 链接到使用 pandas DataFrames 的文档。下面是执行您要查找的操作的代码片段。

import xlwings as xw
bk = xw.Book('BookX.xlsx')
sht = bk.sheets[0]
sht.range('A11').value = df # df is your pandas Dataframe
bk.save()

关于python - 如何使用 pandas 写入 Excel 文档的中间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43986218/

相关文章:

python - 按值比较数据帧

vba - 是否可以以编程方式取代 Excel 中的 native 超链接跟随行为?

vba - Excel VBA - PivotItems 返回无效值

python - 字典列表中的 Pandas DataFrame

python - Pandas - 根据日期差异返回 x 列

python - 对 pandas 中的字符串进行排序

python - 将秒列转换为 hh :mm:ss - Pandas

python - Google 应用引擎中的 Webapp2 session

xml - 使用 VBA 删除 Excel 中的 XML 重复项

python - 如何根据单独列表中的索引值过滤数据框?