[英]reading a formula from a spreadsheet with openxml
I'm reading a spreadsheet in C# using the Openxml library, and I'm parsing the values of the Cell object using InnerText propierty, that returns a String or null . 我正在使用Openxml库在C#中读取电子表格,并且正在使用InnerText属性解析Cell对象的值,该属性返回String或null 。
When in the Cell is present a formula, I get the literal text present in the spreadsheet, like that: 在单元格中出现公式时,我将在电子表格中获得文字文本,如下所示:
=Sheet1!A1Content = Sheet1!A1Content
that is composed by: former formula ( Sheet1!A1 ) + string of the result ( Content ) and this happens also with basics like: =2+24 它由以下组成:以前的公式(Sheet1!A1)+结果的字符串(Content),并且这种情况也会发生,例如= 2 + 24
how do i get only the result of the formula? 我如何只得到公式的结果?
From http://officeopenxml.com/ documentation: 从http://officeopenxml.com/文档:
For a formula, the formula itself is stored within an f element as a child element of c .
对于公式,公式本身存储在f元素内作为c的子元素。 Following the formula is the actual calculated value within a element.
公式之后是元素内的实际计算值。
There is also an example, this open xml for a single cell: 还有一个示例,此打开的xml用于单个单元格:
<c r="B9" s="3" t="str">
<f>SUM(B2:B8)</f>
<v>2105</v>
</c>
So in a Cell
element, there is a child for the Formula
and a child element for the CellValue
. 因此,在
Cell
元素中,该Formula
有一个子元素,而CellValue
有一个子元素。 The InnerText
property of the cell is the concatenated value of those two in your case. 在您的情况下,单元格的
InnerText
属性是这两者的串联值。 If you already have the cell you need you can do the following: 如果您已经拥有该单元,则可以执行以下操作:
static string GetValue(Cell cell)
{
//The ? operator to make sure the 'CellValue' element exists, otherwise return null
return cell.GetFirstChild<CellValue>()?.Text;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.