Pandas 创建一个新的 sheet 而不是在活动数据中添加数据

Pandas create a new sheet instead of adding the data in the active one

我正在使用 openpyxl 创建传播sheet 并添加一些数据。

import pandas as pd
import numpy as np
from openpyxl import Workbook
from openpyxl.utils.dataframe import dataframe_to_rows
from openpyxl import load_workbook

from collections import OrderedDict
workbook = Workbook()
sheet = workbook.active


def fill_static_values():
    sheet["A1"] = "Run No."
    sheet["A2"] = "MLIDMLPA"
    sheet["A48"] = "Patients here"
    
    sheet["B1"] = "Patient"

fill_static_values()

output = "./Name_of_run.xlsx"

workbook.save(filename=output)

然后我的应用程序进行一些数据管理,我想将其中一些数据添加到现有文件中。

book = load_workbook(output)
writer = pd.ExcelWriter(output, engine='openpyxl') 
writer.book = book

## ExcelWriter for some reason uses writer.sheets to access the sheet.
## If you leave it empty it will not know that sheet Main is already there
## and will create a new sheet.

writer.sheets = dict((ws.title, ws) for ws in book.worksheets)

data_no_control.to_excel(writer, "sheet", startrow=2, startcol=3,
                        header=False,
                        index=False)

writer.save()

在此 Whosebug 上找到的解决方案 link

但是,这是在正确的位置创建和添加数据,但在一个名为 sheet2 的新 sheet 中。我做错了什么?

to_excel 的 sheet 名称不正确。 S 应该大写。从更改行 data_no_control.to_excel(writer, "sheet", startrow=2, startcol=3,data_no_control.to_excel(writer, "Sheet", startrow=2, startcol=3,

由于excel中已经有一个sheet,所以正在将数据写入Sheet2

编辑 注意到您正在使用 writer.sheets。如果你想使用希望程序自动从 excel 中提取第一个 sheet,你也可以使用这个...

data_no_control.to_excel(writer, sheet_name=list(writer.sheets.keys())[0], startrow=2, startcol=3,

这将选择第一个 sheet(在你的情况下是唯一的 sheet)作为要更新的工作sheet