【问题标题】:Testing Values In Excel Before Loading to Table在加载到表格之前在 Excel 中测试值
【发布时间】:2015-12-21 04:39:03
【问题描述】:

我使用 C# 从 10 列 Excel 电子表格(到 SQL Server Express)中加载数据,并在加载之前测试空值。我使用的代码适用于非关键字段,但是当它在关键字段中遇到空值时,我收到以下系统生成的错误消息:对象引用未设置为对象的实例。我希望在系统生成错误之前弹出 Response.Write 并停止代码执行。我的代码如下:

if ((string)(range.Cells[rowCount, columnCount] as Excel.Range).Value2.ToString() != null)
{
myVariable = (string)(range.Cells[rowCount, columnCount] as Excel.Range).Value2.ToString();
}

else
{
    Response.Write(@"<script language='javascript'>alert('Update Aborted... \n \nThe load " +
                                    "process has encountered an incomplete record on row " + rowCount + ". Please " +
                                    "correct your Excel file and reload.');</script>");  

    return;
}

【问题讨论】:

    标签: c# excel load


    【解决方案1】:

    条件应该是这样的,在转成字符串之前

    if (range.Cells[rowCount, columnCount] as Excel.Range).Value2!=null 
    

    【讨论】:

    • 谢谢你们两位的cmets。我将合并这些更改。
    【解决方案2】:
    (range.Cells[rowCount, columnCount] as Excel.Range).Value2.ToString()
    

    这里,如果 Value2 为 null,您将有 NullReferenceException

    (string)(range.Cells[rowCount, columnCount] as Excel.Range).Value2.ToString() != null
    

    这种比较毫无意义,因为 (string)(range.Cells[rowCount, columnCount] as Excel.Range).Value2.ToString() 无论如何都不能为空。

    (string)(range.Cells[rowCount, columnCount] as Excel.Range).Value2.ToString()
    

    转换成字符串是没有意义的,因为它已经是字符串了。

    所以我建议将其更改为

    (range.Cells[rowCount, columnCount] as Excel.Range).Value2 != null
    

    此外,范围操作很长,所以最好不要调用此代码两次并创建变量

    object value2 = (range.Cells[rowCount, columnCount] as Excel.Range).Value2;
    

    【讨论】:

      猜你喜欢
      • 2010-11-12
      • 1970-01-01
      • 1970-01-01
      • 2022-08-03
      • 2022-01-21
      • 2010-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多