![](/img/trans.png)
[英]How to merge multiple excel sheet with the same name from different workbooks and save into a new excel workbook using Python
[英]How to save excel sheet to the original workbook?
我有一個這樣的功能:
def DuplicateEachRow():
import pandas as pd
import pathlib
full_path = str(pathlib.Path().absolute()) + '\\' + new_loc
df = pd.read_excel(full_path, header=None, sheet_name='Sheet3')
print(df)
# duplicate the rows:
dup_df = pd.concat([df, df], ignore_index=True)
# using openpyxl
with pd.ExcelWriter(new_loc) as writer:
dup_df.to_excel(writer)
我需要保持相同的功能,而不是將一張紙寫入新文件。 我需要編輯那個特定的工作表並將其保存回我有其他工作表的工作簿。
編輯(更多解釋):我在工作簿中有 4 張工作表,只有一張工作表(Sheet3)我需要使用上面的功能,然后將其保存回工作簿。
這也不起作用,在我保存時指定工作表名稱:
def DuplicateEachRow():
import pandas as pd
import pathlib
full_path = str(pathlib.Path().absolute()) + '\\' + new_loc
df = pd.read_excel(full_path, header=None, sheet_name='GTL | GWL Disclosures')
print(df)
# duplicate the rows:
dup_df = pd.concat([df, df], ignore_index=True)
# using openpyxl
with pd.ExcelWriter(new_loc) as writer:
dup_df.to_excel(writer, sheet_name='GTL | GWL Disclosures')
要在同一個 Excel 中添加新聞表,您必須以追加模式打開文件。 看看下面的代碼:
def DuplicateEachRow():
import pandas as pd
import pathlib
full_path = str(pathlib.Path().absolute()) + '\\' + new_loc
df = pd.read_excel(full_path, header=None, sheet_name='GTL | GWL Disclosures')
print(df)
# duplicate the rows:
# keep the index, so you can sort the rows after
dup_df = pd.concat([df, df])
#sort the rows by the index so you have the duplicate one just after the initial one
dup_df.sort_index(inplace=True)
# using openpyxl
#open the file in append mode
with pd.ExcelWriter(new_loc, mode='a') as writer:
#use a new name for the new sheet
#don't save the header (dataframe columns names) and index (dataframe row names) in the new sheet
dup_df.to_excel(writer, sheet_name='Sheet3', header=None, index=None)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.