我正在使用openpyxl来读取单元格值(excel addin-webservice更新此列。 )
我使用了data_only = True
,但它没有显示当前的单元格值,而是上次Excel读取工作表时存储的值。
wbFile = openpyxl.load_workbook(filename = xxxx,data_only=True)
wsFile = wbFile[c_sSheet]
我如何读取单元格的实际值?
答案 0 :(得分:86)
wb = openpyxl.load_workbook(filename, data_only=True)
data_only
标志有帮助。
答案 1 :(得分:9)
正如@ alex-martelli所说,openpyxl不会评估公式。使用openpyxl打开Excel文件时,您可以选择读取公式或最后计算的值。如果您指出公式依赖于加载项,则缓存的值永远不会准确。作为文件规范之外的加载项,它们永远不会受到支持。相反,您可能希望查看可以与Excel运行时交互的xlwings之类的内容。
答案 2 :(得分:3)
遇到同样的问题。无论单元格是什么,都需要读取单元格值:标量,具有预先计算值的公式或不具有这些值的公式,容错性优于正确性。
该策略非常简单:
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}")
答案 3 :(得分:3)
data_only:甚至读取公式单元格的值。
keep_vba:仅当您使用启用了宏的Excel时才使用
file_location = 'C:\Arpan Saini\Monsters\Project_Testing\SecCardGrad\SecCardGrad_Latest_docs\Derived_Test_Cases_Secure_Card_Graduate.xlsm'
wb = load_workbook(file_location, keep_vba=True, data_only=True)
答案 4 :(得分:0)
正如@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,即期望值。
当处理具有非常复杂的公式和工作表之间的引用的电子表格时,我发现它非常有用。
答案 5 :(得分:0)
我通过以下方式解决了这个问题:
import xlwings
from openpyxl import load_workbook
data = load_workbook('PATH_TO_YOUR_XLSX_FILE')
data['sheet_name']['A1'].value = 1
data.save('PATH_TO_YOUR_XLSX_FILE')
excel_app = xlwings.App(visible=False)
excel_book = excel_app.books.open('PATH_TO_YOUR_XLSX_FILE')
excel_book.save()
excel_book.close()
excel_app.quit()
data = load_workbook('PATH_TO_YOUR_XLSX_FILE', data_only=True)
我希望这可以帮助您...
答案 6 :(得分:0)
Xlcalculator可以评估单元格。
from xlcalculator import ModelCompiler
from xlcalculator import Model
from xlcalculator import Evaluator
filename = r'xxxx.xlsm'
compiler = ModelCompiler()
new_model = compiler.read_and_parse_archive(filename)
evaluator = Evaluator(new_model)
val1 = evaluator.evaluate('First!A2')
print("value 'evaluated' for First!A2:", val1)
输出为:
“第一” A2的“评估”值:0.1
答案 7 :(得分:0)
如果发现“ REF!”,我发现data_only选项无法正常工作。工作表中的错误单元格。 对于我的小型测试xlsx文件中的每个单元格值,Openpyxl返回None。 对我来说,打开Excel并修复单元格后,data_only可以完美地工作。 我使用的是openpyxl 3.0.3