[英]Overwrite an excel sheet with pandas dataframe without affecting other sheets
I want to overwrite an existing sheet in an excel file with Pandas dataframe but don't want any changes in other sheets of the same file.我想用 Pandas dataframe 覆盖 excel 文件中的现有工作表,但不希望对同一文件的其他工作表进行任何更改。 How this can be achieved.如何做到这一点。 I tried below code but instead of overwriting, it is appending the data in 'Sheet2'.我尝试了下面的代码,但不是覆盖,而是将数据附加到“Sheet2”中。
import pandas as pd
from openpyxl import load_workbook
book = load_workbook('sample.xlsx')
writer = pd.ExcelWriter('sample.xlsx', engine = 'openpyxl')
writer.book = book
writer.sheets = dict((ws.title, ws) for ws in book.worksheets)
df.to_excel(writer, 'sheet2', index = False)
writer.save()
I didn't find any other option other than this, this would be a quick solution for you.除了这个,我没有找到任何其他选择,这对你来说是一个快速的解决方案。
I believe still there'sno direct way to do this, correct me if I'm wrong.我相信仍然没有直接的方法可以做到这一点,如果我错了,请纠正我。 That's the reason we need to play with this logical ways.这就是我们需要使用这种合乎逻辑的方式的原因。
import pandas as pd
def write_excel(filename,sheetname,dataframe):
with pd.ExcelWriter(filename, engine='openpyxl', mode='a') as writer:
workBook = writer.book
try:
workBook.remove(workBook[sheetname])
except:
print("Worksheet does not exist")
finally:
dataframe.to_excel(writer, sheet_name=sheetname,index=False)
writer.save()
df = pd.DataFrame({'Col1':[1,2,3,4,5,6], 'col2':['foo','bar','foobar','barfoo','foofoo','barbar']})
write_excel('PRODUCT.xlsx','PRODUCTS',df)
Let me know if you found this helpful, igonre if you need any other better solution.如果您觉得这有帮助,请告诉我,如果您需要任何其他更好的解决方案,请告诉我。
Since Pandas version 1.3.0 on_sheet_exists
is an option of ExcelWriter
.由于 Pandas 版本 1.3.0 on_sheet_exists
是ExcelWriter
的一个选项。 It can be used as such:它可以这样使用:
import pandas as pd
with pd.ExcelWriter("my_sheet.xlsx",engine="openpyxl",mode="a",on_sheet_exists="replace") as writer:
pd.write_excel(writer,df)
Since none of the ExcelWriter
methods or properties are public, it is advised to not use them.由于ExcelWriter
方法或属性都不是公共的,因此建议不要使用它们。
Similar to Gavaert's answer... For Pandas 1.3.5, add the 'if_sheet_exists="replace"' option:类似于 Gavaert 的回答...对于 Pandas 1.3.5,添加 'if_sheet_exists="replace"' 选项:
import pandas as pd
with pd.ExcelWriter("file.xlsx", engine="openpyxl", mode="a", if_sheet_exists="replace") as writer:
df.to_excel(writer, 'Logs', index=False)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.