简体   繁体   English

如何将新工作表保存到现有 excel 工作簿的开头?

[英]How to save a new sheet to the beginning of an existing excel workbook?

I found part of the answer from this post and it was very useful https://stackoverflow.com/a/42375263/13765378我从这篇文章中找到了部分答案,它非常有用https://stackoverflow.com/a/42375263/13765378

However, every time I ran this code with new data, a new sheet gets added to the end of a workbook.但是,每次我使用新数据运行此代码时,都会在工作簿的末尾添加一个新工作表。 After a while, it is quite an effort to get to that new sheet that was just added.过了一会儿,要找到刚刚添加的新工作表是相当困难的。 Is there a way to specify adding to the beginning of the workbook, so it will be the default sheet when we open the workbook?有没有办法指定添加到工作簿的开头,所以当我们打开工作簿时它将是默认工作表?

This will help you.use the second line.this uses openpyxl module help link https://openpyxl.readthedocs.io/en/stable/tutorial.html这将对你有所帮助。使用第二行。这使用 openpyxl 模块帮助链接https://openpyxl.readthedocs.io/en/stable/tutorial.html

ws1 = wb.create_sheet("Mysheet") # insert at the end (default)

ws2 = wb.create_sheet("Mysheet", 0) # insert at first position

Thanks to Vignesh's answer, and Thanks to and modifying the code from writing pandas data frame to existing workbook I got the following code to work: [Every time the program is run, a new sheet will be created at the beginning of the workbook and contains (new) data.感谢 Vignesh 的回答,感谢并修改将pandas 数据框写入现有工作簿的代码,我得到了以下代码工作:[每次运行程序时,都会在工作簿的开头创建一个新工作表并包含(新数据。 Rest of the code just testing out the function append_df_to_excel()] The function append_df_to_excel() seems over-kill for what I need to do, but for now I could not find a better and cleaner way to do it. Rest of the code just testing out the function append_df_to_excel()] The function append_df_to_excel() seems over-kill for what I need to do, but for now I could not find a better and cleaner way to do it.

I also do not understand why saving the workbook at the end will not save the data.我也不明白为什么最后保存工作簿不会保存数据。

import os
from openpyxl import load_workbook
import xlsxwriter
import pandas as pd
from datetime import datetime

filename = r'C:\test\test.xlsx'
if not os.path.exists(filename):
    wb = xlsxwriter.Workbook(filename)
    wb.close()   

def append_df_to_excel(filename, df, sheet_name='Sheet1', startrow=None,
                       truncate_sheet=False, 
                       **to_excel_kwargs):
    """
    Append a DataFrame [df] to existing Excel file [filename]
    into [sheet_name] Sheet.
    If [filename] doesn't exist, then this function will create it.

    Parameters:
      filename : File path or existing ExcelWriter
                 (Example: '/path/to/file.xlsx')
      df : dataframe to save to workbook
      sheet_name : Name of sheet which will contain DataFrame.
                   (default: 'Sheet1')
      startrow : upper left cell row to dump data frame.
                 Per default (startrow=None) calculate the last row
                 in the existing DF and write to the next row...
      truncate_sheet : truncate (remove and recreate) [sheet_name]
                       before writing DataFrame to Excel file
      to_excel_kwargs : arguments which will be passed to `DataFrame.to_excel()`
                        [can be dictionary]

    Returns: None
    """


    # ignore [engine] parameter if it was passed
    if 'engine' in to_excel_kwargs:
        to_excel_kwargs.pop('engine')

    writer = pd.ExcelWriter(filename, engine='openpyxl')

    if not os.path.exists(filename):
        wb = xlsxwriter.Workbook(filename)
        wb.close()     
    try:
        # try to open an existing workbook
        writer.book = load_workbook(filename)

        # get the last row in the existing Excel sheet
        # if it was not specified explicitly
        if startrow is None and sheet_name in writer.book.sheetnames:
            startrow = writer.book[sheet_name].max_row
        # truncate sheet
        if truncate_sheet and sheet_name in writer.book.sheetnames:
            # index of [sheet_name] sheet
            idx = writer.book.sheetnames.index(sheet_name)
            # remove [sheet_name]
            writer.book.remove(writer.book.worksheets[idx])
            # create an empty sheet [sheet_name] using old index
            writer.book.create_sheet(sheet_name, idx)
            # writer.book.create_sheet(sheet_name, 0) #not working

        # copy existing sheets
        writer.sheets = {ws.title:ws for ws in writer.book.worksheets}
    except FileNotFoundError:
        # file does not exist yet, we will create it
        pass

    if startrow is None:
        startrow = 0

    # write out the new sheet
    df.to_excel(writer, sheet_name, startrow=startrow, **to_excel_kwargs)

    # save the workbook
    writer.save()

A = [[0,1,2],[3,4,5],[6,7,8],[9,10,11]]
df = pd.DataFrame(A, columns=list('XYZ'))

newSheet = "New_" + datetime.now().strftime('%Y-%m-%d_%H%M%S')
wb = load_workbook(filename)
ws = wb.create_sheet(newSheet, 0)
wb.save(filename)

append_df_to_excel(filename, df, sheet_name="Old2", startrow=1, startcol=1)
append_df_to_excel(filename, df, sheet_name="Old3", index=False)
append_df_to_excel(filename, df, sheet_name="Old1", startcol=2, index=False) 
append_df_to_excel(filename, df, sheet_name=newSheet, columns=df.columns.values, startrow=0, startcol=0, index=False)

# wb.save(filename) # Do not do this, will get nothing written to workbook

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在现有工作簿中添加新工作表? - How to add new sheet in an existing workbook? 如何将excel表保存到原始工作簿? - How to save excel sheet to the original workbook? Python-使用现有格式保存新的Excel工作表 - Python - save new Excel sheet with existing format 如何使用Python合并来自不同工作簿的多个同名excel工作表并保存到新的excel工作簿中 - How to merge multiple excel sheet with the same name from different workbooks and save into a new excel workbook using Python 从Excel发送电子邮件:RangetoHTML现有工作表而不是新工作簿 - Email From Excel: RangetoHTML existing sheet instead of new workbook 使用 VB 代码将新工作表添加到现有 Excel 工作簿 - Add new sheet to existing Excel workbook with VB code 协助 Excel VBA 参考单元格将工作表移动到新工作簿并保存 - Assistance with Excel VBA Reference Cell to Move Sheet to new workbook and save 如何使用 vbs 脚本复制活动的 Excel 工作表并将其保存到新工作簿中? - How to copy an active excel sheet and save it into a new workbook using a vbs script? 写入新工作簿,而不是现有工作簿中的工作表 - Writing to new workbook instead of sheet in existing workbook 将 Excel 工作表移动到另一个具有不同工作表名称的现有工作簿作为新工作表 - Move an Excel Work Sheet to Another existing workbook with different sheet name as new sheet
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM