使用Openpyxl在现有工作表中从指定的列和行开始写入现有Excel文件。

3

我一直在寻找这个问题的答案,想要将其写入现有的Excel工作表,并从特定的行和列开始。然而,像dataframe_to_rows这样的方法并没有从单元格的特定位置开始写入。 现在我正在使用自定义循环来编写此内容,但想知道是否有更好的方法。 循环的工作方式如下:

import pandas as pd
import numpy as np
from openpyxl import load_workbook
from openpyxl.utils import get_column_letter
df = pd.DataFrame(np.random.randn(20, 4), columns=list('ABCD'))
file = "C:\\somepath\\some_existing_file.xlsx"
wb = load_workbook(filename=file, read_only=False)
ws = wb['some_existing_sheet']

##Fill up the row and column needed
stcol = 5
strow = 5

## Writing the column header
for c in range(0,len(df.columns)):
    ws[get_column_letter(c+stcol)+str(strow)].value = df.columns[c]
## Writing the data
for r in range(0,len(df)):
    for c in range(0,len(df.columns)):
       ws[get_column_letter(c+stcol)+str(strow+r+1)].value = df.iloc[r][c]
wb.save(file)

请告诉我是否有更好的方式在单元格中写入特定位置。如果这是一个重复的问题,也可以合并到原始线程中。 我还有另一种方法,使用xlsx writer,但这会删除现有表格中的所有其他数据。

import win32com.client as win32
excel = win32.gencache.EnsureDispatch('Excel.Application') # opens Excel
writer = pd.ExcelWriter(file', engine='xlsxwriter')
df.to_excel(writer, sheet_name='abc', startrow=5, startcol=5,index=False)
writer.save()

不需要使用 get_column_letter - Charlie Clark
需要创建一个数字循环来查找每个单元格并从每个数据帧记录中分配值。不确定是否遗漏了什么。 - Sanjoy
1个回答

2
代替
ws[get_column_letter(c+stcol)+str(strow)]

你可以使用

ws.cell(column=c+stcol, row=strow) 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接