OpenXML读取错误的单元格值(如果为整数)

时间:2018-11-13 18:11:06

标签: c# excel openxml openxml-sdk

我正在使用此代码读取单元格值;

SELECT CASE WHEN Res = 'ABC' THEN 'ABC' ELSE 'Other' END AType,
       CASE WHEN Res = 'DEF' THEN 'DEF' ELSE 'Other' END BType
FROM
(
SELECT Substring(AccNo,5,3) Res --You write SUBSTRING() just one time
From MainTable
) T

我正在读取行的第一个单元格并获取值。我的擅长就是这样。

            var cell = row.Elements<Cell>().FirstOrDefault();
            var stringId = Convert.ToInt32(cell.InnerText);

            var cellValue = workbookPart.SharedStringTablePart.SharedStringTable
                .Elements<SharedStringItem>().ElementAt(stringId).InnerText;

因此,当行为3时,将 A B 1 x name1 2 y name2 3 1 name3 的值设置为1,将stringId的值设置为“ cellValue”,但应为1。

1 个答案:

答案 0 :(得分:1)

您需要检查单元格的DataType,因为“ 1”存储为实际数字,而不是共享字符串表中的字符串。

var cell = row.Elements<Cell>().FirstOrDefault();
string cellValue = null;

if (cell.DataType != null && cell.DataType == CellValues.SharedString)
{
    //it's a shared string so use the cell inner text as the index into the 
    //shared strings table
    var stringId = Convert.ToInt32(cell.InnerText);
    cellValue = workbookPart.SharedStringTablePart.SharedStringTable
        .Elements<SharedStringItem>().ElementAt(stringId).InnerText;
}
else
{
    //it's NOT a shared string, use the value directly
    cellValue = cell.InnerText;
}

有两点需要注意: 1)如果未提供,则默认类型为Number 2)上面的代码未处理其他类型。日期特别尴尬。