c#格式化CSV

时间:2017-09-26 08:34:46

标签: c# csv

我的程序中有一些包含字符串的变量,我需要将其放到CSV文件中。

例如,

var1 = "abc";    
var2 = "bbb";    
var3 = "    
-vvv    
-xxx     
-zzz    
-ccc    
-ddd    
"; // Var 3 is a multiline string, need it to be put in one cell

CSV文件:

Col1   Col2   Col3 (1 cell)
abc    bbb    -vvv
              -xxx
              -zzz
              -ccc
              -ddd

然后在下一行:  var1(newVal)var2(newVal)var3(newVal)

问题是如何形成var x转到colx等的CSV文件。

我的代码如下所示:

string getDir = Directory.GetCurrentDirectory();

DirectoryInfo d = new DirectoryInfo(@getDir + "\\src");
FileInfo[] Files = d.GetFiles("*.txt"); 
string str = "";
foreach(FileInfo file in Files )
{
  str = str + "," + file.Name;            
}

string lines="col1," + "col2," + "col3," + "col4 ," + "col5," + "col6," + "\n";

int ncheck = 1; 
int countFiles = d.GetFiles().Length; 

int vcheck = 0; 



    while (ncheck <= /*countFiles*/1) 
    {
        var getfile = str.Split(',')[ncheck];
        lines = lines + getfile;    
        while ( vcheck <= 4) 
        {
        string startSTR = "a1,a2,a3,a4,a5";
        var starts = startSTR.Split(',')[vcheck];

        string endSTR = "b1,b2,b3,b4,b5";
        var ends = endSTR.Split(',')[vcheck];


        string St = System.IO.File.ReadAllText(d + "\\" + getfile);

        int pFrom = St.IndexOf(starts) + starts.Length;
        if (St.IndexOf(starts) == -1 || St.IndexOf(ends) == -1) {pFrom=0;};
        int pTo = St.LastIndexOf(ends);
        if (St.IndexOf(starts) == -1 || St.IndexOf(ends) == -1) {pTo=pFrom+0;};




        String result = St.Substring(pFrom, pTo - pFrom);
        if (St.IndexOf(starts) == -1 || St.IndexOf(ends) == -1) {result="Not found";};

        /*Console.WriteLine(starts);
        Console.WriteLine(result);          
        Console.WriteLine(ends);*/
        Console.WriteLine(lines);
        lines = lines + "," + result;
        Console.WriteLine(lines);
        vcheck++;
        }
        lines = lines + "\n";
        ncheck++;
        vcheck=0;
    }

System.IO.StreamWriter filetxt = new System.IO.StreamWriter(@getDir + "\\test.csv");
filetxt.WriteLine(lines);

filetxt.Close();

在src目录中查找txt文件,然后搜索字符串,最后保存到CSV文件。正如我之前所说的,我在格式化文档时遇到问题,因为一个字符串有多行,需要在一个单元格中。

有没有更好的方法来解决这个问题?

1 个答案:

答案 0 :(得分:0)

如果您的字符串或换行符中有逗号,则必须引用字符串

原文:John Smith,Jr 引用:“John Smith,Jr”

如果字符串中有引号,请通过双引号将其转义

原文:John“Johnny”Smith 引用:John“”Johnny“”Smith

如果字符串中有逗号/换行符和引号,则将两个规则组合在一起。

原文:John“Johnny”Smith,Jr 引用:“John”“Johnny”“Smith,Jr”

这是我写的一个处理正确引用的扩展方法。像这样使用它:

var properQuoted = myString.CsvQuote();

    static public string CsvQuote(this string text)
    {
        if (text == null)
        {
            return string.Empty;
        }

        bool containsQuote = false;
        bool containsComma = false;
        bool containsNewline = false;
        bool containsCR = false;
        int len = text.Length;
        for (int i = 0; i < len && (containsComma == false || containsQuote == false); i++)
        {
            char ch = text[i];
            if (ch == '"')
            {
                containsQuote = true;
            }
            else if (ch == ',')
            {
                containsComma = true;
            }
            else if (ch == '\r')
            {
                containsCR = true;
            }
            else if (ch == '\n')
            {
                containsNewline = true;
            }
        }

        bool mustQuote = containsComma || containsQuote || containsCR || containsNewline;

        if (containsQuote)
        {
            text = text.Replace("\"", "\"\"");
        }

        if (mustQuote)
        {
            return "\"" + text + "\"";  // Quote the cell and replace embedded quotes with double-quote
        }
        else
        {
            return text;
        }
    }