Openpyxl保留公式但复制值

时间:2016-11-30 06:12:22

标签: python-3.x openpyxl

我的工作簿有6张。最后3张是一堆公式,我目前手动复制并将值粘贴到前3张中。我使用wb.copy_worksheet()来制作副本并将工作簿加载为data_only = True。但是,当我保存时,由于将其加载为data_only,公式都已消失。有没有办法可以复制值但保留公式?这些纸张太大而无法逐个细胞。

继承我的代码:

import openpyxl

wb = openpyxl.load_workbook("symbols.xlsx", data_only=True)

ws = wb.get_sheet_names()
print (ws)


Value = ws[0:3] #set equal to first 3 sheets


BB = ws[3:7] #set equal to last 3 sheets      

for s in range(0, len(Value)):

    CopyBB = wb.copy_worksheet(wb[BB[s]])  #copy from bb sheet
    CopyBB.title = Value[s]


myorder = [6, 7, 8, 3, 4, 5, 0, 1, 2]   #this is to reorder the sheets that got copied.

wb._sheets =[wb._sheets[i] for i in myorder]

wb.remove_sheet(wb.worksheets[8])
wb.remove_sheet(wb.worksheets[7])
wb.remove_sheet(wb.worksheets[6])

wb.worksheets[0].title = "Securities Values" 
wb.worksheets[1].title = "Indices Values"
wb.worksheets[2].title = "Currencies Values"


return wb.save("symbols.xlsx")

1 个答案:

答案 0 :(得分:0)

我有类似的问题。您必须使用='MVSM!A1',其中MVSM是工作表名称,然后A1是单元格值。只需在使用openpyxl时分配单元格值时使用它。