如何基于现有C#代码统计拆分后各CSV的独立行数
按COMPID拆分CSV并添加独立行数统计行的修改方案
以下是基于你现有代码的修改版本,实现了每个输出CSV文件的独立行数统计:
//Get values needed for the file's names string chargeMonth = DateTime.Now.ToString("yyyyMM"); var fileCreationDate = DateTime.Now.ToString("yyyyMMdd"); string fileCreationTime = DateTime.Now.ToString("HHmmss"); string constVal = "MLL"; string fileType = "HIYUV-CHEVRA"; //Initiate variables string[] values; string header, sumRow; string line, compId; string inputFile = "records.CSV"; //Create a Dictionary that will have CompanyId as keys (for example 10, 1000) Dictionary<string, System.IO.StreamWriter> outputFiles = new Dictionary<string, System.IO.StreamWriter>(); // 新增字典:记录每个COMPID对应的记录行数(不含表头和统计行) Dictionary<string, int> rowCounts = new Dictionary<string, int>(); //Read from records.csv which is the complete datatable from database using (System.IO.StreamReader file = new System.IO.StreamReader(@"D:\" + inputFile, Encoding.Default)) { //header line ( columns ) header = file.ReadLine(); //As long as line isnt null while ((line = file.ReadLine()) != null) { //Seperates with comma each value (total of 24 values-columns) values = line.Split(",".ToCharArray()); //Gets company_Id compId = values[3]; //Checks if Key doesnt contain CompanyId inside the dictionary if (!outputFiles.ContainsKey(compId)) { //This will be the created file's name string outputFileName = constVal + "-" + fileType + "-" + (String.Format("{0:00000}", Int32.Parse(compId))) + "-" + chargeMonth + "-" + fileCreationDate + "-" + fileCreationTime + ".CSV"; //Adding keys/values to dictionary outputFiles.Add(compId, new System.IO.StreamWriter(@"D:\" + outputFileName)); // 初始化当前COMPID的行数为0 rowCounts.Add(compId, 0); // 写入表头 outputFiles[compId].WriteLine(header); } // 写入当前数据行 outputFiles[compId].WriteLine(line); // 对应COMPID的行数加1 rowCounts[compId]++; } // 为每个文件写入统计行并关闭 foreach (var kvp in outputFiles) { string currentCompId = kvp.Key; StreamWriter writer = kvp.Value; // 生成统计行(格式可根据需求调整) sumRow = $"{String.Format("{0:00000}", Int32.Parse(currentCompId))},{chargeMonth},{fileCreationDate},{fileCreationTime},{String.Format("{0:00000}", rowCounts[currentCompId])}"; writer.WriteLine(sumRow); writer.Close(); } }
关键改动说明:
- 新增
rowCounts字典,专门跟踪每个COMPID对应的数据行数,解决原代码无法区分各文件行数的问题 - 在创建新输出文件时,初始化对应COMPID的行数为0
- 每写入一条数据行后,将对应COMPID的计数加1
- 在关闭所有文件前,遍历每个输出文件,根据统计的行数生成专属统计行并写入
注:原代码中重复添加表头的问题你已知晓,此版本优先保证行数统计功能可用,若后续需要优化可再调整表头写入逻辑。
内容的提问来源于stack exchange,提问作者user20622377
相关产品推荐
相关产品推荐

