Reputation: 352
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
}
}
Upvotes: 2
Views: 15741
Reputation: 23
to those who are searching to write in two column just add ;
string.Format("{0};{1}", dl[i], xl[i]);
Upvotes: 1
Reputation: 1
I found the easiest way to do it was:
using (StreamWriter sw = File.CreateText("newfile.csv"))
{
for (int i = 0; i < threshhld; i++)
{
//writing two columns right next to eachother
sw.WriteLine(dl[i] + "," + xl[i]);
}
}
Upvotes: 0
Reputation: 10068
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]);
Upvotes: 2
Reputation: 52250
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);
Upvotes: 7