我正在尝试使用 openpyxl 库从 python 中基于宏的 xls 文件(.xlsm)读取内容。我想从单元格中读取值,但我获取的是宏公式,而不是单元格中宏的填充值。 有什么方法可以从 python 中的单元格内容中获取值吗?
######## 下面是示例代码###########
import 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)
if __name__ == "__main__":
template_path = "C:\\macro_xls\\sample_test.xlsm"
output_path = "C:\\macro_xls\\sample_test_output.xlsm"
generate_output_file(template_path, output_path)
您可以设置
data_only=True
从带有公式的单元格中读取值。
from openpyxl import load_workbook
wb = load_workbook("yourData.xlsm", data_only=True)
ws = wb['test']
cell = ws['A1']
value = cell.value
来自doc:
(bool) – 控制带有公式的单元格是否具有 公式(默认)或上次 Excel 读取时存储的值 片data_only