如何使用python 3从excel中的宏单元格读取值

时间:2017-09-01 12:50:40

标签: python vba openpyxl xlsm

我正在尝试使用openpyxl库从python中读取基于宏的xls文件(.xlsm)的内容。我想从单元格读取值,但我得到宏公式而不是单元格中宏的填充值。 有没有办法从python中的单元格内容中获取值?

##下面是示例代码

导入openpyxl

def generate_output_file(template_path,output_path):

# Load/open the existing workbook template
old_wb = openpyxl.load_workbook(template_path, keep_vba=True)
old_sheet = old_wb['sheet1']

# Sample logic for inserting data in sheet1 which will trigger macro and populate some values
# in other cells(eg. C276) of sheet1
old_sheet['B55'] = 'abcd'

# Save the modified workbook
old_wb.save(output_path)

# Now open the modified file in same instance
new_wb = openpyxl.load_workbook(output_path, data_only=True)
new_sh = new_wb.get_sheet_by_name('sheet1')

# this should show populated values of macro cell, but showing None
print(new_sh['C276'].value)

如果名称 ==" 主要":

template_path = "C:\\macro_xls\\sample_test.xlsm"
output_path = "C:\\macro_xls\\sample_test_output.xlsm"
generate_output_file(template_path, output_path)

1 个答案:

答案 0 :(得分:0)

您可以将Nodes/bnode.go:16:58: AMethod redeclared in this block previous declaration at Nodes/anode.go:15:58 Nodes/bnode.go:20:60: BMethod redeclared in this block previous declaration at Nodes/anode.go:19:60 设置为使用公式从单元格中读取值。

data_only=True

来自doc

  

from openpyxl import load_workbook wb = load_workbook("yourData.xlsm", data_only=True) ws = wb['test'] cell = ws['A1'] value = cell.value (bool) - 控制具有公式的单元格是否具有   公式(默认)或上次Excel读取时存储的值   片