【问题标题】:String Array index not holding null value字符串数组索引不包含空值
【发布时间】:2015-07-16 05:09:27
【问题描述】:

我有一个字符串数组,但空值没有被索引和存储

例如,如果我有一个数组 { "one", "", "three" },array[0] 的值为 1,array[1] 的值变为 3 而不是 "",为什么是 null 值删除,下一个值的索引变为空值。

这是我的代码,我正在使用 Open XML SDK 读取 Excel 单元格并将其存储到数组中。

foreach (var row in rows)
{
        int i = 0;
        string[] rowData = new string[9];
        var cells = row.Elements<Cell>();

        foreach (var cell in cells)
        {
            if (cell != null)
            {
                var index = Int32.Parse(cell.CellValue.Text);

                if (cell.DataType != null)
                {
                    rowData[i] = GetSharedStringItemById(workbookPart, index);
                }
            }
            i++;
        }

        var store = new UserStore<User>(context);
        var manager = new UserManager<User>(store);
        var user = new User
        {
            UserName = rowData[0],
            FirstName = rowData[1],
            LastName = rowData[2],
            Email = rowData[3],
            EmailConfirmed = true,
            RegisterdOn = now,
            Employer = new Employer()
            {
                CompanyName = rowData[4],
                AddressLine1 = rowData[5],
                AddressLine2 = rowData[6],
                City = rowData[7],  <---if value of city is null, the value of PostCode is used?
                PostCode = rowData[8],
            }
        };

        var result = manager.Create(user, "123456");
        if (result.Succeeded)
        {
            manager.AddToRole(user.Id, "Employer");
        }
}

【问题讨论】:

  • 根据您发布的代码,问题是cell.CellValue.Text 属性返回了错误的索引,或者GetSharedStringItemById() 方法滥用了传递给它的索引。但是您的代码示例严重不足。如果您想要一个实际的答案,请发布a good, minimal, complete code example 以可靠地重现问题。

标签: c# arrays asp.net-mvc openxml-sdk


【解决方案1】:

如果有帮助,请查看以下内容

//在转换为整数之前检查单元格的值是否为空

if(cell.CellValue.Text != null){

var index = Int32.Parse(cell.CellValue.Text);

//将转换的值添加到数组中

rowData[i] = GetSharedStringItemById(workbookPart, index);

  } 

//in case the value contained in a cell is null, then assign either "" or null 

rowData[i] = "";

另外,请注意“”与 null 不同。如果你测试 "" 和 null 是否相等,测试的结果将是错误的。

【讨论】:

    猜你喜欢
    • 2021-08-06
    • 1970-01-01
    • 2016-02-03
    • 2022-09-22
    • 2015-12-15
    • 2022-08-19
    • 1970-01-01
    • 2011-03-31
    • 1970-01-01
    相关资源
    最近更新 更多