gpt4 book ai didi

python - 创建新工作表而不是使用现有工作表

转载 作者:太空宇宙 更新时间:2023-11-04 04:31:10 24 4
gpt4 key购买 nike

我正在将数据从一个工作簿复制到另一个工作簿。问题是 pandas 正在创建一个名为“sheet_name1”的新工作表,而不是使用“sheet_name”。我使用 openpyxl 作为 Pandas 引擎。能帮忙分析下原因吗?

    input_file = "C:\Automations\FastenersAudit\ClassfiedExports\\" + str(export)
output_file = "C:\Automations\FastenersAudit\Templates\\" + str(template)

input_df = pd.read_excel(io=input_file, skiprows=1)
output_df = pd.read_excel(io=output_file, skiprows=4)
headings = list(output_df.head())
writer = pd.ExcelWriter(output_file, engine="openpyxl")
writer.book = openpyxl.load_workbook(output_file)

for each_heading in headings:
try:
output_df[each_heading] = input_df[each_heading]
except KeyError:
continue

output_df = output_df.loc[:, :'Total Attributes']
output_df = output_df.drop(labels='Total Attributes', axis=1)
output_df.to_excel(writer, sheet_name="Attribute Analysis", na_rep='', index=False, startrow=5, engine="openpyxl")
writer.save()
writer.close()

最佳答案

略微编辑的版本:非常感谢您的解决方案。稍作修改即可完美运行。

    writer.sheets = {ws.title: ws for ws in writer.book.worksheets}

for sheetname in writer.sheets:
if sheetname == 'Attribute Analysis':
output_df.to_excel(writer, sheet_name=sheetname, na_rep='', index=False, startrow=5, engine="openpyxl", header=False)
writer.save()

原答案:

我认为您需要 startrow 和 maxrow 函数以及writer.sheets 来读取工作表名称:

writer.sheets = {ws.title: ws for ws in book.worksheets} 
for sheetname in writer.sheets:

output_df.to_excel(writer,sheet_name=sheetname,startrow=writer.sheets[sheetname].max_row, index = False,header= False)
writer.save()

关于python - 创建新工作表而不是使用现有工作表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52620354/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com