我有一个课程,我正在写这样的CSV文件:
csvWriter.Configuration.RegisterClassMap(new AffidavitFullAndPartialMapping(detailLevel));
csvWriter.WriteRecords(allAffidavits);
我发送" allAffidavits"要写入的集合,我想手动再向CSV写入一行。最后一行将是所有空格,除了最后一个单元格需要包含特定值。
所以我想我会做the official CsvHelper documentation中描述的事情(在一个名为"写单个字段")的部分:
如果您愿意,也可以手动编写每个字段。
var csv = new CsvWriter( textWriter ); foreach( var item in list ) { csv.WriteField( "a" ); csv.WriteField( 2 ); csv.WriteField( true ); csv.NextRecord(); }
但我怎么知道要手动写多少个空白单元?这与我的CSV文件中已有的列数相同。由于映射(请参阅本文顶部的第一行代码),它可能会动态变化。
谢谢,
埃利泽
答案 0 :(得分:1)
You could loop through all the property and reference maps and count them. It's possible to set a higher index, so it would probably be better to find the highest index instead. There is an internal method that should probably be made public that you could use for this.
internal int GetMaxIndex()
{
if( PropertyMaps.Count == 0 && ReferenceMaps.Count == 0 )
{
return -1;
}
var indexes = new List<int>();
if( PropertyMaps.Count > 0 )
{
indexes.Add( PropertyMaps.Max( pm => pm.Data.Index ) );
}
indexes.AddRange( ReferenceMaps.Select( referenceMap => referenceMap.GetMaxIndex() ) );
return indexes.Max();
}
For now just copy this. If it works for you, submit a ticket in GitHub to have this method made public.
答案 1 :(得分:0)
我替换了上面的两行:
csvWriter.Configuration.RegisterClassMap(new AffidavitFullAndPartialMapping(detailLevel));
csvWriter.WriteRecords(allAffidavits);
用这个:
var classMapping = new AffidavitFullAndPartialMapping(detailLevel);
csvWriter.Configuration.RegisterClassMap(classMapping);
csvWriter.WriteRecords(allAffidavits);
然后我能够获得CSV中的列数:
int numberOfColumnsInCsv = classMapping.PropertyMaps.Count;
在一个循环中 - 多次迭代 - 执行:
csvWriter.WriteField(string.Empty);