【问题标题】:CSVhelper any way to ignore "=" present in CSVCSVhelper 以任何方式忽略 CSV 中存在的“=”
【发布时间】:2020-02-19 14:38:51
【问题描述】:

我有一个生成 CSV 数据的应用程序。此应用程序“有帮助”包括使用 = 作为引用 0 填充数字数据的前导的 Excel 修复,以防止 Excel 解释器吃掉前导 0。

我想使用CSVHelper 来读取这些记录。但是,当映射到数字时,CSVhelper 会报告带有 = 前缀的这些值的错误。

除了搜索/替换以拉出“=”之外,有没有办法告诉 CSVhelper 忽略前导等于并成功处理?我看到了在书面输出中包含 = 但不允许它们在解析中的选项。

这是一个示例记录:

"XYZ INC","R1G202113","R2G",="202113","D-SRS PRO FLD SM/2",157.49,122.53,True,50,50,0.00 ,1,假,"N",4.00,6.00,8.00,6.00,""

对此表示赞赏。

【问题讨论】:

    标签: c# csv csvhelper


    【解决方案1】:

    这是一个猜测,可能有更好的方法,但也许你可以用你的映射做这样的事情:

    public class MyData
    {
        //map the raw input to this field as a string
        public string MappedIntField {get;set;}=null;
    
    
        // use an integer property not mapped to any column to shadow the string, and lazy-convert to an integer the first time you read it.
        public int ActualIntField 
        {
            get {
                if (MappingReady || string.IsNullOrEmpty(MappedIntField)) return _ActualIntField;
    
                //clean up the extra = character.
                if (MappedIntField[0] == '=') MappedIntField = MappedIntField.Substring(1);
    
                int result; 
                if (int.TryParse(MappedIntField, out result))
                {
                     _ActualIntField = result;
                     MappingReady = true;
                     return result;
                }
                return _ActualIntField;             
            }
            set {
                _ActualIntField = value;
                MappingReady = true;
            }
        }
        private int _AcutalIntField;
        // We don't want to re-parse the string on every read, so also flag when this work is done. You could also use a nullable int? to do this.
        private bool MappingReady = false;
    
    }
    

    【讨论】:

    • 谢谢乔尔,没想到将其映射为一个字段。我想知道它是否没有分隔符是一个问题,IE没有额外的“,”
    • @Davery 我明白你在说什么。起初我没有注意到 = 符号不在引号内,而是在引号之前。我希望这种基本技术仍然有效,但 CSVHelper 也会将引号作为数据的一部分导入,因此在解析整数之前您只需要多一点代码即可将它们去掉。
    • @Davery 我可以找到一种使用CSVHelper生成带有=的CSV的方法,但不是读取此类内容的方法。请参阅 CSVHelper issue 527CsvHelper.Contrib issue 7。我希望有类似的东西可供阅读,但我找不到。
    • ="0123" 将在 Excel 中导入公式(在 Excel 2013 中测试)。导入这样的值需要csv.Configuration.BadDataFound = null;(或者可以按照上面显示的方式完成)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-24
    相关资源
    最近更新 更多