Skip to main content
 首页 » 编程设计

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

2024年12月31日9itcoder

我正在将数据从一个工作簿复制到另一个工作簿。问题是 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()