我想知道是否有一种方法可以创建使用
load_workbook
方法创建的工作簿对象的深层副本。
我想创建一个像这样的流程(该项目将位于 Jypter Notebook 中):
#Cell 1
import openpyxl
#Cell 2
wb1 = load_workbook("c:\temp\"abc123.xlsm", keep_vba=True) #This file is large and takes several minutes to load
#Cell 3
wb2 = wb1 #This doesn't create a deep copy but I would like something that creates a deep copy
#Cell 4
#Changes to wb2 happen here e.g. sheets get deleted. I would like to go back and rerun cell 2 so that I can reuse the wb1 variable without needing to load the file again.
我尝试使用 IDE 对 xlsx 文件进行快速测试。 这会从原始工作表中生成两个新的 xlsx 文件,一个在单元格“B10”中包含新工作表“newsheet”,其中包含“hello”,另一个在单元格“E10”中包含新工作表“Sheet10”和“Hello There” .
from openpyxl import load_workbook
from io import BytesIO
file = 'foo.xlsx'
with open(file, "rb") as fh:
wb_data = BytesIO(fh.read())
wb1 = load_workbook(wb_data)
wb2 = load_workbook(wb_data)
wb1.create_sheet('newsheet')
wb2.create_sheet('Sheet10')
ws1 = wb1['newsheet']
ws2 = wb2['Sheet10']
ws1.cell(10, 2).value = "Hello"
ws2.cell(10, 5).value = "Hello There"
wb1.save('save1.xlsx')
wb2.save('save2.xlsx')