如何读取电子表格单元格的显示值而不是公式?
我有一个程序,通过访问电子表格中的“文本”成员来读取单元格的值(通过 COM)。当我使用Excel 2003时,我的程序正确返回了单元格的显示值。现在我使用 OpenOffice Calc,而是取回单元格中的公式 ('=SUM(F8:F10)')。
更复杂的是,我使用了一个名为 AutomateIT! 的工具来让我像对待 Excel 一样对待 Calc ,所以可能是这导致了问题,而不是 Calc.
我的程序是用 Python 编写的,我使用 win32com.client 库来创建 COM 调度程序。 这是 Python 代码的本质(对于包含公式的单元格,“empty”函数始终返回 false):
from win32com.client import Dispatch
def empty(cell):
"""Returns false if the specified cell has a non-zero value in it"""
val = sheet.Range(cell).Text
return val == 0.0 or val == '' or val == None
xlApp = Dispatch('Excel.Application') # Actually opens OpenOffice Calc, thanks to AutomateIT!
xlApp.Workbooks.Open('myfile.ods')
sheet = xlApp.Workbooks(1).Sheets(1)
if empty('F12'):
sheet.Range('C2').Value = 'X' # Never get here because F12 is a formula cell
...
在empty() 中使用“Value”会给出与“Text”相同的值。
I have a program that reads the value of a cell in a spreadsheet (via COM) by accessing its 'Text' member. When I was using Excel 2003, my program correctly returned the displayed value of the cell. Now I am using OpenOffice Calc, and instead I am getting back the formula in the cell ('=SUM(F8:F10)').
To complicate matters, I am using a tool called AutomateIT! to let me treat Calc as if it was Excel, so it might be that that's causing the problem instead of Calc.
My program is in Python, and I use the win32com.client library to create the COM dispatcher.
This is the essence of the Python code (the 'empty' function always returns false for a cell containing a formula):
from win32com.client import Dispatch
def empty(cell):
"""Returns false if the specified cell has a non-zero value in it"""
val = sheet.Range(cell).Text
return val == 0.0 or val == '' or val == None
xlApp = Dispatch('Excel.Application') # Actually opens OpenOffice Calc, thanks to AutomateIT!
xlApp.Workbooks.Open('myfile.ods')
sheet = xlApp.Workbooks(1).Sheets(1)
if empty('F12'):
sheet.Range('C2').Value = 'X' # Never get here because F12 is a formula cell
...
Using 'Value' in empty() gives the same value as 'Text'.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为什么不在 Excel 中将文件保存为 CVS,然后使用 csv 模块从文件中提取数据?这将为您提供单元格的数据而不是公式。
Why not just have the file saved as a CVS in Excel and then use the csv module to pull the data from the file? That will give you the data of the cell rather than the formula.