gpt4 book ai didi

c# - 如果整数,OpenXML 读取错误的单元格值

转载 作者:行者123 更新时间:2023-12-04 22:30:28 25 4
gpt4 key购买 nike

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

            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。

最佳答案

您需要查看 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)还有其他类型没有被上面的代码处理。约会特别尴尬。

关于c# - 如果整数,OpenXML 读取错误的单元格值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53287127/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com