Write in next column in csv file c#

13,506

Solution 1

You are not writing an Excel file. You are writing a CSV file which is compatible with Excel. CSV stands for "Comma separated values," meaning that you should use the comma as a column separator.

So... change this:

sw.WriteLine(dl[i]);
sw.WriteLine(xl[i]); // i want to write this in another column 

To this:

var line = String.Format("{0},{1}", dl[i], xl[i]);
sw.WriteLine(line);

Solution 2

As already explained in other answer, CSV files are a special type of text file, where we have multiple records of data, one row per line. (Like a table row in RDBMS tables). Now, each line/row can have multiple data-part(s) or columns or data (like data column in a table row), separated by comma ','.

Basically a CSV file represents a table of data. It is not an Excel file, but can be open with MS Excel and edited easily.

So, a typical csv data file will look like

EmployeeId,Name,Dept

1,John,CSharp

2,Eric,Compiler

So, to make a new data-row, you just write the contents in a new line. And to mark the columns, you separate them with comma. As asked by op, if each value of dl and xl are to be created as columns in the csv file, they should be written in a line separated by comma. This can be achieved by changing the code inside for loop to

sw.WriteLine(dl[i] + "," + xl[i]);

Here + is used to concatenate three string values, but for more stings or even for this, it can be done in a cleaner way using

string.Format("{0},{1}", dl[i], xl[i]);

Solution 3

to those who are searching to write in two column just add ;

string.Format("{0};{1}", dl[i], xl[i]);
Share:
13,506
mbugr
Author by

mbugr

Updated on June 25, 2022

Comments

  • mbugr
    mbugr almost 2 years

    I have two list every list have different data i want to add the lists data to csv file my problem how to write in the next column.

    The two list is dl, xl i want to write xl in column and dl in another column

    this my code

    using (StreamWriter sw = File.CreateText("list.csv"))
                {
                    for (int i = 0; i < dl.Count; i++)
                    {
                        // the two list have the same count 
                        sw.WriteLine(dl[i]);
                        sw.WriteLine(xl[i]); // i want to write this in another column 
                    }
                }
    
  • Adrian Efford
    Adrian Efford over 2 years
    I have been looking for such an answer and you are the only one who could help me out. Thank you!