栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

导入CSV文件错误:包含列定界符的列值

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

导入CSV文件错误:包含列定界符的列值

一个警告:我不是常规的C#编码器。

但是无论如何,此代码执行以下操作:

它打开一个名为C: Input.TXT的文件

它搜索每一行。如果该行有五个以上的逗号,则它将所有多余的逗号从倒数第三个字段中删除(注释)

它将结果写入C: Output.TXT-这是您实际需要导入的结果

可以进行许多改进:

  • 从连接管理器获取文件路径
  • 错误处理
  • 经验丰富的C#程序员可能会在代码中做到这一点

请记住,您的软件包将需要对相应文件夹的写权限

public void Main(){    // Search the file and remove extra commas from the third last field    // Extended from pre at    // http://stackoverflow.com/questions/1915632/open-a-file-and-replace-strings-in-c-sharp    // Nick McDermaid    string sInputLine;    string sOutputLine;    string sDelimiter = ",";    String[] sData;    int iIndex;    // open the file for read    using (System.IO.FileStream inputStream = File.OpenRead("C:\Input.txt"))    {        using (StreamReader inputReader = new StreamReader(inputStream))        { // open the output file using (StreamWriter outputWriter = File.AppendText("C:\Output.txt")) {     // Read each line     while (null != (sInputLine = inputReader.ReadLine()))     {         // Grab each field out         sData = sInputLine.Split(sDelimiter[0]);         if (sData.Length <= 6)         {  // 6 or less fields - just echo it out  sOutputLine = sInputLine;         }         else         {  // line has more than 6 pieces   // We assume all of the extra commas are in the notes field  // Put the first three fields together  sOutputLine =      sData[0] + sDelimiter +      sData[1] + sDelimiter +      sData[2] + sDelimiter;  // Put the middle notes fields together, excluding the delimiter  for (iIndex=3; iIndex <= sData.Length - 3; iIndex++)  {      sOutputLine = sOutputLine + sData[iIndex] + " ";  }  // Tack on the last two fields  sOutputLine = sOutputLine +      sDelimiter + sData[sData.Length - 2] +      sDelimiter + sData[sData.Length - 1];         }         // We've evaulted the correct line now write it out         outputWriter.WriteLine(sOutputLine);     } }        }    }    Dts.TaskResult = (int)Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success;}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/431729.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号