问题
I am writing this piece of code. My objective is to set a value in a specific cell of this excel file. The code is running quite ok and exits with no error, but the cell A1 remains blank. How can I fix this?
import openpyxl
wb = load_workbook('Test.xlsm')
ws = wb.worksheets[1]
ws.cell(row=1, column=1).value = 999999
wb.save('Test.xlsm')
回答1:
from openpyxl import Workbook
from openpyxl import load_workbook
wb = load_workbook('Test.xlsm',keep_vba=True)
ws = wb['Sheet1']
ws.cell(row=1,column=1).value = 9999999
wb.save('Test.xlsm')
You need to have 'keep_vba' enabled since you are trying to modify an .xlsm(Excel Macro Enabled Workbook),I don't know why but this seems to work.
wb = load_workbook('Test.xlsm',keep_vba=True)
回答2:
The line wb = load_workbook('Test.xlsm')
should be
wb = openpyxl.load_workbook('Test.xlsm')
based on what you have provided.
Also, are you looking in sheet 2? The line
wb.worksheets[1]
specifies sheet 2 as sheets are zero-indexed.
来源:https://stackoverflow.com/questions/49470871/how-write-to-xlsm-using-openpyxl