【问题标题】:OpenXML reading wrong cell value if integer如果整数,OpenXML 读取错误的单元格值
【发布时间】:2018-11-13 18:11:06
【问题描述】:

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

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

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

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

     A    B
 1   x    name1
 2   y    name2
 3   1    name3

所以当行为 3 时,stringId 的值设置为 1,cellValue 设置为“x”,但应该是 1。

【问题讨论】:

    标签: c# excel openxml openxml-sdk


    【解决方案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)还有其他类型没有被上面的代码处理。约会特别尴尬。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-13
      • 1970-01-01
      • 1970-01-01
      • 2016-09-25
      • 1970-01-01
      • 2017-05-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多