简体   繁体   中英

How to export data in csv file from C# console application?

I want to extract values of a variable in CSV file from ac# console application.

Variable has unlimited values like it is the position value from a stream when the stream ends variable values also finishes. I have seen many examples on the internet but none of them answers my question.

Here is what I found.

var file = @"C:\SavedBTData.csv";

using (var stream = File.AppendText(file))
{
    for (int i = 0; i < ToBT.Count(); i++)
    {
        BTdata[i] = ToBT[i].ToString();

    }
    string csvRow = string.Format("{0},{1},{2},{3},{4},{5},{6},{7}", BTdata[0], BTdata[1], BTdata[2], BTdata[3], BTdata[4], BTdata[5], BTdata[6], BTdata[7]);

    stream.WriteLine(csvRow);
}

But here in string csvRow line .... I don't know how much values I get from that variable moreover I have to save data in just 1 column.

Anyone with a possible suggestion.

Use String.Join method to combine all values of array:

string csvRow = string.Join(",", BTdata);

Also, you do not need to convert all to string:

string csvRow = string.Join(",", ToBT);
       var file = @"D:\\awaisFile.csv";
        using (var stream = File.AppendText(file))
        {
            /* initialize elements of array n */
            for (i = 0; i < num1.Count(); i++)
            {
                Console.Write("Enter value of 'num1'");
                Console.WriteLine(i + 1);
                num1[i] = int.Parse(Console.ReadLine());
                temp1[i] = num1[i].ToString();

                Console.Write("Enter value of 'num2'");
                Console.WriteLine(i + 1);
                num2[i] = int.Parse(Console.ReadLine());
                temp2[i] = num2[i].ToString();

                res[i] = multiplyNum(num1[i], num2[i]);

                Console.WriteLine("Element1[{0}] = {1}", i, res[i]);
                temp3[i] = res[i].ToString();

                string csvRow = string.Format("{0},{1},{2}", temp1[i], temp2[i], temp3[i]);

                stream.WriteLine(csvRow);

            }

        }

I used this way and it worked fine for me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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