将新工作表添加到 python 中的现有工作簿

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40385689/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 23:28:10  来源:igfitidea点击:

Add a new sheet to a existing workbook in python

pythonexcel

提问by fsociety

I have browsed almost all the previous threads, but still cannot get this working.I am trying to add a new sheet to an existing workbook. My code works,but it keeps on adding a lot more (so many of them actually) sheets. I can't figure out the solution.Below is my code

我已经浏览了几乎所有以前的线程,但仍然无法正常工作。我正在尝试向现有工作簿添加新工作表。我的代码有效,但它不断添加更多(实际上有很多)工作表。我想不出解决方案。下面是我的代码

from openpyxl import load_workbook
wb2 = load_workbook('template.xlsx')
from xlutils.copy import copy as xl_copy
wb = xl_copy(wb2)
wb.create_sheet('sid1')
wb.save('template.xlsx')

回答by Daniel

If you want to add a sheet to an existing spreadsheet, just go ahead and add the new sheet to the file instead of copying your loadobject and trying to add the new sheet to it.

如果要将工作表添加到现有电子表格中,只需继续将新工作表添加到文件中,而不是复制load对象并尝试将新工作表添加到其中。

from openpyxl import load_workbook
wb2 = load_workbook('template.xlsx')
wb2.create_sheet('sid1')
wb2.save('template.xlsx')