本帖最后由 阿奇_o 于 2021-8-18 20:41 编辑
这的确有点鸡肋啊,无论openpyxl,还是 xlwings , 本质上都需要"打开"Excel文件,才能获取到公式的计算结果。。
# 参考:
# https://stackoverflow.com/questions/28517508/read-excel-cell-value-and-not-the-formula-computing-it-openpyxl
# https://groups.google.com/g/openpyxl-users/c/GbBOnOa8g7Y
# https://stackoverflow.com/questions/28517508/read-excel-cell-value-and-not-the-formula-computing-it-openpyxl
# https://stackoverflow.com/questions/23350581/openpyxl-1-8-5-reading-the-result-of-a-formula-typed-in-a-cell-using-openpyxl/23362361
from openpyxl import Workbook, load_workbook
# wb = Workbook()
# sh1 = wb['Sheet']
# sh1['A1'] = 100
# sh1['B1'] = 200
# sh1['C1'] = '=A1+B1'
# wb.save('openpyxl_formula_test.xlsx')
# 解决办法:让公式先计算出结果
from win32com.client import Dispatch
import os
def just_open(filename):
'''利用用微软的Excel不显示地打开,让公式得以计算'''
xlApp = Dispatch("Excel.Application")
xlApp.Visible = False
xlBook = xlApp.Workbooks.Open(os.path.abspath(filename)) # 需要决定路径哦
xlBook.Save()
xlBook.Close()
just_open(filename="openpyxl_formula_test.xlsx")
# wb2 = load_workbook('openpyxl_formula_test.xlsx', data_only=False) # 默认读取数据和公式
wb2 = load_workbook('openpyxl_formula_test.xlsx', data_only=True) # 只读取"数据"
# 注:对于公式,若没有经过计算的公式,将识别为 None;
# 计算过的公式(如用Excel打开一次),则读取公式计算的结果值。
print(wb2['Sheet']['C1'])
# print(wb2['Sheet']['C1'].internal_value) # 据说有些版本用这个读取
print(wb2['Sheet']['C1'].value)
# ws2 = wb2['Sheet']
# for row in ws2.values:
# for v in row:
# print(v)
# 那 用 xlwings 试试?
import xlwings as xw
# xw.App().visible = True
with xw.App(visible=False) as xapp: # 隐藏(不显示)打开的Excel
wb3 = xw.Book("openpyxl_formula_test.xlsx") # 会直接打开Excel。。
# wb3 = xw.Book("test.xlsx") # 注:若不加上面的 visible参数 会直接打开Excel;
# 不加with语句需要自己关闭Excel应用,否则再次打开时多个Excel并存可能冲突
# s = xw.sheets # 居然用 xw的sheets方法,也行
print(wb3.sheets)
print(xw.sheets['Sheet'].range('C1').value)
print(wb3.sheets['Sheet'].range('C1').value)
# wb3.close()
# 参考:
# https://www.geeksforgeeks.org/working-with-excel-files-in-python-using-xlwings/
# https://stackoverflow.com/questions/38995281/open-a-workbook-with-xlwings-without-making-it-visible
|