简体   繁体   English

使用 python 删除 excel 中的工作表

[英]Deleting sheet in excel using python

m1 = pd.ExcelFile('C:\\Users\\a\\Desktop\\1.xlsx')
df1 = pd.read_excel(m1, sheet_name='Raw Data')
df1.head()

m2 = pd.read_excel('C:\\Users\\a\\Desktop\\stbd.xlsx')
m2.head()

# drop all values in m1
df1 = df1.drop(labels=range(0 , df1.shape[0]) , axis=0)
df1.shape

I wanted to delete data in a sheet of excel workbook and overwrite the same sheet with new data and to refresh the pivot table in next sheet with new data.我想删除 excel 工作簿工作表中的数据,并用新数据覆盖同一张工作表,并用新数据刷新下一张工作表中的 pivot 表。 But once I use this code part and run it, all other sheets(sheets which has pivot tables) in the workbook is deleted.但是,一旦我使用此代码部分并运行它,工作簿中的所有其他工作表(具有 pivot 表的工作表)都会被删除。 Can someone support me with this?有人可以支持我吗?

You have to read all the sheets of the excel file and then save them all including the changed one您必须阅读 excel 文件的所有表格,然后将它们全部保存,包括更改的表格

m1 = pd.ExcelFile('C:\\Users\\a\\Desktop\\1.xlsx')
df1 = pd.read_excel(m1, sheet_name=list(m1.sheet_names))

#change the specific sheet
df1["sheet to change"] = 'house' #something to change

writer = pd.ExcelWriter("output_excel_file.xlsx", engine = 'xlsxwriter')

for sheet in m1.sheet_names:
    df1[sheet].to_excel(writer,index=False, sheet_name=sheet)

writer.save()

Something like that.类似的东西。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM