我正在使用openpyxl来读取单元格值(excel addin-webservice更新此列。)
我使用过data_only = True
,但它没有显示当前的单元格值,而是上次Excel读取工作表时存储的值。
wbFile = openpyxl.load_workbook(filename = xxxx,data_only=True)
wsFile = wbFile[c_sSheet]
我如何读取单元格的实际值?
wb = openpyxl.load_workbook(filename, data_only=True)
data_only
旗帜帮助。
正如@ alex-martelli所说,openpyxl不会评估公式。使用openpyxl打开Excel文件时,您可以选择读取公式或最后计算的值。如果您指出公式依赖于加载项,则缓存的值永远不会准确。作为文件规范之外的加载项,它们永远不会受到支持。相反,您可能希望查看类似xlwings的内容,它可以与Excel运行时进行交互。
面临同样的问题。无论这些单元格是什么,都需要读取单元格值:标量,具有预计算值的公式或没有它们的公式,其中容错优先于正确性。
该策略非常简单:
pycel
评估它;pycel
对公式的有限支持或有一些错误),警告并返回None。我创建了一个隐藏所有这些机器的类,并为读取单元格值提供了简单的界面。
如果正确性优于容错,则可以很容易地修改类,以便它在步骤4中引发异常。
希望它会帮助某人。
from traceback import format_exc
from pathlib import Path
from openpyxl import load_workbook
from pycel.excelcompiler import ExcelCompiler
import logging
class MESSAGES:
CANT_EVALUATE_CELL = ("Couldn't evaluate cell {address}."
" Try to load and save xlsx file.")
class XLSXReader:
"""
Provides (almost) universal interface to read xlsx file cell values.
For formulae, tries to get their precomputed values or, if none,
to evaluate them.
"""
# Interface.
def __init__(self, path: Path):
self.__path = path
self.__book = load_workbook(self.__path, data_only=False)
def get_cell_value(self, address: str, sheet: str = None):
# If no sheet given, work with active one.
if sheet is None:
sheet = self.__book.active.title
# If cell doesn't contain a formula, return cell value.
if not self.__cell_contains_formula(address, sheet):
return self.__get_as_is(address, sheet)
# If cell contains formula:
# If there's precomputed value of the cell, return it.
precomputed_value = self.__get_precomputed(address, sheet)
if precomputed_value is not None:
return precomputed_value
# If not, try to compute its value from the formula and return it.
# If failed, report an error and return empty value.
try:
computed_value = self.__compute(address, sheet)
except:
logging.warning(MESSAGES.CANT_EVALUATE_CELL
.format(address=address))
logging.debug(format_exc())
return None
return computed_value
# Private part.
def __cell_contains_formula(self, address, sheet):
cell = self.__book[sheet][address]
return cell.data_type is cell.TYPE_FORMULA
def __get_as_is(self, address, sheet):
# Return cell value.
return self.__book[sheet][address].value
def __get_precomputed(self, address, sheet):
# If the sheet is not loaded yet, load it.
if not hasattr(self, '__book_with_precomputed_values'):
self.__book_with_precomputed_values = load_workbook(
self.__path, data_only=True)
# Return precomputed value.
return self.__book_with_precomputed_values[sheet][address].value
def __compute(self, address, sheet):
# If the computation engine is not created yet, create it.
if not hasattr(self, '__formulae_calculator'):
self.__formulae_calculator = ExcelCompiler(self.__path)
# Compute cell value.
computation_graph = self.__formulae_calculator.gen_graph(
address, sheet=sheet)
return computation_graph.evaluate(f"{sheet}!{address}")
正如@Charlie Clark所说,你可以使用xlwings
(如果你有MS Excel)。这是一个例子
假设你有一个带有公式的excel表,例如我用openpyxl
定义一个
from openpyxl import Workbook, load_workbook
wb=Workbook()
ws1=wb['Sheet']
ws1['A1']='a'
ws1['A2']='b'
ws1['A3']='c'
ws1['B1']=1
ws1['B2']=2
ws1['B3']='=B1+B2'
wb.save('to_erase.xlsx')
如上所述,如果我们再次使用openpyxl
加载excel,我们将无法获得评估公式
wb2 = load_workbook(filename='to_erase.xlsx',data_only=True)
wb2['Sheet']['B3'].value
你可以使用xlwings
来获得excel评估的公式:
import xlwings as xw
wbxl=xw.Book('to_erase.xlsx')
wbxl.sheets['Sheet'].range('B3').value
返回3,预期值。
我发现在使用非常复杂的公式和工作表之间的引用的电子表格时非常有用。