如何在不使用Interop的SSIS C#脚本中修复含多余逗号的CSV文件?
用SSIS C#脚本修复带引号且末尾多逗号的CSV文件
完全可行,无需依赖Excel Interop,直接通过C#脚本即可完成CSV文件的自动修复,以下是具体实现方案:
核心处理思路
问题的关键是精准移除每条记录末尾的多余逗号,同时避免误删带引号字符串内部的逗号。根据CSV的格式特点,提供两种处理方式:
方式一:简单逐行处理(适用于无跨行字段的CSV)
如果你的CSV没有跨行的带引号字段(每条记录单独占一行),可以直接用正则表达式匹配并移除行尾的多余逗号(包括可能伴随的空格)。
在SSIS中添加脚本任务,编写如下C#代码:
using System.IO; using System.Text.RegularExpressions; using Microsoft.SqlServer.Dts.Runtime; public class ScriptMain { public void Main() { // 从SSIS变量获取源文件和目标文件路径 string sourceFile = Dts.Variables["User::SourceCSVPath"].Value.ToString(); string targetFile = Dts.Variables["User::TargetCSVPath"].Value.ToString(); using (StreamReader reader = new StreamReader(sourceFile)) using (StreamWriter writer = new StreamWriter(targetFile)) { string line; while ((line = reader.ReadLine()) != null) { // 移除行尾的逗号及后续空格 string cleanedLine = Regex.Replace(line, @",\s*$", ""); writer.WriteLine(cleanedLine); } } Dts.TaskResult = (int)ScriptResults.Success; } }
方式二:专业CSV解析(适用于含跨行字段的CSV)
如果CSV存在跨行的带引号字段(比如某字段内容包含换行符),简单的逐行处理会破坏字段结构,此时建议使用TextFieldParser类(属于Microsoft.VisualBasic.FileIO命名空间,C#可直接引用)来正确解析CSV字段,再重新生成规范的CSV内容。
对应的C#脚本示例:
using System.IO; using Microsoft.VisualBasic.FileIO; using Microsoft.SqlServer.Dts.Runtime; public class ScriptMain { public void Main() { string sourceFile = Dts.Variables["User::SourceCSVPath"].Value.ToString(); string targetFile = Dts.Variables["User::TargetCSVPath"].Value.ToString(); using (TextFieldParser parser = new TextFieldParser(sourceFile)) using (StreamWriter writer = new StreamWriter(targetFile)) { parser.TextFieldType = FieldType.Delimited; parser.SetDelimiters(","); parser.HasFieldsEnclosedInQuotes = true; // 开启带引号字段识别 parser.TrimWhiteSpace = true; // 可选:去除字段前后的空格 while (!parser.EndOfData) { try { string[] fields = parser.ReadFields(); // 重新拼接字段,自动避免末尾逗号 string cleanedLine = string.Join(", ", fields); writer.WriteLine(cleanedLine); } catch (MalformedLineException ex) { // 记录异常日志,可根据需求调整 Dts.Events.FireError(0, "CSV修复失败", $"异常行信息:{ex.Message}", string.Empty, 0); } } } Dts.TaskResult = (int)ScriptResults.Success; } }
注意事项
- 需确保SSIS脚本任务的变量已正确配置(源文件路径、目标文件路径);
- 若使用
TextFieldParser,需在脚本项目中添加对Microsoft.VisualBasic程序集的引用; - 处理前建议备份源文件,避免数据丢失。
内容的提问来源于stack exchange,提问作者Chris Singleton
相关产品推荐
相关产品推荐

