Pandas / Openpyxl:在特定单元格上写入带有左角的数据框

问题描述 投票:0回答:1

我想使用 openpyxl 在 Excel 工作表中编写一个表格。

我的 Pandas 数据框看起来像这样:

df = pd.DataFrame({
   "A": [1, 3, 5],
   "B": [2, 4, 6],
})

我想创建一个如下所示的 xlsx 文件(单元格 D9 中数据框的右上角):

我怎样才能做到这一点,这意味着是否有最好的方法通过使用迭代所有数据帧逐个单元格地写入来做到这一点? 谢谢

python pandas openpyxl
1个回答
0
投票
import openpyxl
import pandas as pd

df = pd.DataFrame({
"A": [1, 3, 5],
"B": [2, 4, 6],
})

# Create a new workbook and select the active sheet
wb = openpyxl.Workbook()
ws = wb.active

# Define the range of cells to write the DataFrame
start_row = 9
start_col = 3

# Write the DataFrame to the worksheet
for idx, row in df.iterrows():
    for col in range(len(row)):
        column_letter = openpyxl.utils.get_column_letter(start_col+col)
        ws[f'{column_letter}{idx+start_row}'] = df.iloc[idx, col]

# Save the workbook to a file
wb.save('example.xlsx')
© www.soinside.com 2019 - 2024. All rights reserved.