如何获得值显示在单元格从.xlsx使用开放的XML c#
本文关键字:XML xlsx 何获得 显示 单元格 | 更新日期: 2023-09-27 18:15:17
我是c#和XML的新手,所以请耐心等待我的无知。
我有这个问题:
我需要从。xlsx文件中获得单元格值。我可以用XlGetCellValue方法做到这一点。但是当一个单元格(例如sheet1中的A2)从另一个单元格(sheet2中的B2)获取值时
XlGetCellValue("", "Sheet1", "A2")
返回Sheet2!B2Joe
。
或者当单元格包含计算时(如=C2+D2), XlGetCellValue(...)
返回C2+D2120
是否有简单的方法来获得"Joe"answers"120"的值?
这里是关于如何使用Open XML SDK 2.5获取单元格值的MSDN链接。这里提供了一个代码示例:
如何:检索电子表格文档中单元格的值(Open XML SDK)
如果您还没有下载OpenXMLSDKToolV25,那么使用openxmlml可能是一件痛苦的事情。msi(生产力工具).
基本上它是一个反射工具。你可以打开一个excel文档和工具创建所有你需要从头开始构建相同的代码。
CellValue它只用于value。使用公式必须处理单元格公式。
。我创建了一个excel文件在A1 = 1256在B1 = 2在C1 "=A1*B1"使用OpenXMLSDKTool打开文件得到:
public Row GenerateRow()
{
Row row1 = new Row(){ RowIndex = (UInt32Value)1U, Spans = new ListValue<StringValue>() { InnerText = "1:3" } };
Cell cell1 = new Cell(){ CellReference = "A1" };
CellValue cellValue1 = new CellValue();
cellValue1.Text = "1256";
cell1.Append(cellValue1);
Cell cell2 = new Cell(){ CellReference = "B1" };
CellValue cellValue2 = new CellValue();
cellValue2.Text = "2";
cell2.Append(cellValue2);
Cell cell3 = new Cell(){ CellReference = "C1" };
CellFormula cellFormula1 = new CellFormula();
cellFormula1.Text = "A1*B1";
CellValue cellValue3 = new CellValue();
cellValue3.Text = "2512";
cell3.Append(cellFormula1);
cell3.Append(cellValue3);
row1.Append(cell1);
row1.Append(cell2);
row1.Append(cell3);
return row1;
}
你可以注意到CellValue和CellFormula都是Cell的子元素。假设你可以检索行r你可以这样写:
Cell c = r.Elements<Cell>().ElementAt(2);
CellValue cv = c.CellValue;
CellFormula cf = c.CellFormula;