[英]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.