【问题标题】:How to set change Linq to excel Null string values?如何将 Linq 更改为 excel Null 字符串值?
【发布时间】:2021-05-17 11:34:42
【问题描述】:

我有一个模型可以使用 LINQ 将对象列表转换为 excel。

public class Model{
  public string Name { get; set; }
  public string Date { get; set; }
}

我正在使用

var result = excelQueryFactory.Warksheet<Model>(0);

但我的 excel 在名称单元格中有 Null 测试。但它们应该是空的。所以我的Name 属性填充了Null 文本。在填充模型时如何使这些文本值变得更优秀?

【问题讨论】:

    标签: c# .net linq-to-excel


    【解决方案1】:

    也许这种非常常见的模式会满足您的要求。

    public class Model {
    
        private string _name;
    
        public string Name { 
    
            get => _name; 
    
            set {
                _name = (value == null_value) ? empty_value : value;
            }
        } 
    }
    

    【讨论】:

      【解决方案2】:
      public class Model
      {
          private string _Name;
      
          public string Name
          {
              get { return _Name; }
              set
              {
                  if (string.IsNullOrWhiteSpace(value) || value.ToLower() == "null")
                      _Name = null;
                  else
                      _Name = value;
              }
          }
      
          public string Date { get; set; }
      }
      

      【讨论】:

        【解决方案3】:

        您可以将以下转换添加到您的 excel 工厂对象:

        excelQueryFactory.AddTransformation<Model>(x => x.Date, cellValue => cellValue??string.Empty);
        excelQueryFactory.AddTransformation<Model>(x => x.Name, cellValue => cellValue??string.Empty);
        

        【讨论】:

        • 我可以为所有类型的字符串属性添加反射变换吗?
        • 是的,我想是的。 (如果回答对你有帮助,请点赞,谢谢)
        【解决方案4】:

        您是否尝试过使用 LINQ 中的 SELECT 选项将空值转换为字符串?

        var result = excelQueryFactory.Warksheet<Model>(0)
            .Select(x => new Model{
                Name = x.Name ?? string.Empty,
                Date = x.Date
            });
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-04-15
          • 2012-08-13
          • 2015-04-05
          相关资源
          最近更新 更多