【问题标题】:EPPlus: Detect and deal with "number stored as text"EPPlus:检测和处理“数字存储为文本”
【发布时间】:2015-02-25 13:40:29
【问题描述】:

我们使用 EPPlus 库读取 Excel 电子表格并获取各种单元格值。

当某些单元格值是“数字存储为文本”时,可能会出现一个问题。我们可以要求用户尽量不要使用带有此警告的电子表格,但如果可以的话,我想在不严重污染我的代码的情况下处理它。

当使用“数字存储为文本”读取单元格值时,我们会看到以下内容:

int foo = ws.Cells[row, column].GetValue<int>(); // foo comes out as 0
string bar = Convert.ToString(ws.Cells[row, column].Value); // bar comes out as "7"

理想情况下,我希望有一种方法可以正确读取所有值,而不必为电子表格中的每个单元格解析字符串。

【问题讨论】:

标签: c# excel epplus


【解决方案1】:

我不会将其标记为已接受,因为它实际上并没有回答我的问题,所以如果有人知道如何检测“数字存储为文本”,那么请回答,我会接受你。

最后我用方法调用代替了.GetValue&lt;int&gt;()等。您甚至可以根据您的目的将其转换为扩展方法以提高可读性。

方法如下:

    private int GetInt(object value)
    {
        if (value == null)
        {
            return 0;
        }
        else if (value is double)
        {
            return Convert.ToInt32(value);
        }
        else if (value is string)
        {
            var intValue = 0;
            Int32.TryParse((string)value, out intValue);
            return intValue;
        }
        else
        {
            throw new Exception("Unexpected value type.");
        }
    }

我这样称呼它:

int foo = GetInt(ws.Cells[row, column].Value); // foo comes out as 7

【讨论】:

    猜你喜欢
    • 2020-05-19
    • 1970-01-01
    • 1970-01-01
    • 2012-07-20
    • 2017-01-01
    • 2016-01-27
    • 2013-01-07
    • 2011-02-28
    • 1970-01-01
    相关资源
    最近更新 更多