简体   繁体   English

将c#数组导出到带有标题的csv文件

[英]Export c# array to csv file with title

I tried to export an 2-D array from c# to a csv file but last several rows are missing in the csv file.I don't know where the problem is in my code. 我试图将二维数组从c#导出到一个csv文件,但是csv文件中缺少最后几行。我不知道问题出在我的代码中。

First,I'd like to know if my code is not correct? 首先,我想知道我的代码是否不正确?

Second,is it possible to add a title for each row in the csv file . 其次,是否可以为csv文件中的每一行添加标题。

Thanks in advance 提前致谢

Here is an example of my array in c# 这是我在C#中的数组的示例

 string[,] array=new string[]{{2000,2},{2001,4}}

I want to a result like this in csv file with title 我想在带有标题的csv文件中得到这样的结果

  Date   C1
  2000   2
  2001   4

My code: 我的代码:

 var outfile=new.streamwriter(@"fileadress.csv");
 for(int i=0;i<array.GetUpperbound(0);i++)
 {
   string content="";
  for(int j=0;j<array.GetUpperbound(1);j++)
   {
     content+= array[i,j]+";";
   }
  outfile.WriteLine(content);

 }

There are a lot of problems in the code shown. 显示的代码中存在很多问题。 The most important is the wrong usage of GetUpperBound that return the 'upperbound' of your array, and your example this upperbound is 1 (not 2) thus the < array.UpperBound skips the last position in the array. 最重要的是GetUpperBound的错误用法返回了数组的“ GetUpperBound ”,在您的示例中,上限为1(而不是2),因此< array.UpperBound跳过了数组中的最后一个位置。

I suggest a reworking of your code in this way 我建议以这种方式修改您的代码

// This is an array of strings right?
string[,] array=new string[,]{{"2000","2"},{"2001","4"}};

// Use a StringBuilder to accumulate your output
StringBuilder sb = new StringBuilder("Date;C1\r\n");
for (int i = 0; i <= array.GetUpperBound(0); i++)
{
    for (int j = 0; j <= array.GetUpperBound(1); j++)
    {
         sb.Append((j==0 ? "" : ";") + array[i, j]);        
    }
    sb.AppendLine();
}

// Write everything with a single command 
File.WriteAllText(@"fileadress.csv", sb.ToString());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM