【发布时间】:2018-02-10 13:02:44
【问题描述】:
我正在尝试使用 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)
如果 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)
【问题讨论】:
-
这个问题和你的问题类似:stackoverflow.com/questions/45949630/…
-
@marni .. 感谢您的回复,但我在使用 openpyxl 加载工作簿时使用 data_only=True,但我使用它然后它给了我 None
-
我附上了示例代码,其中单元格 B276 包含来自宏的自动填充值.... import openpyxl output_path = "C:\\Users\\DEMO\\macro_xls\\output\\ sample_test.xlsm" wb = openpyxl.load_workbook(output_path, data_only=True) new_sh = wb.get_sheet_by_name('II.8') print(new_sh['B276'].value)
-
向我们展示您尝试过的代码如何?