-1

I search how to output data into csv file by using c#, in csv I need 4 columns, but now all data is written in one column. What I done so far is :

 var first = barcode[i];
 var second = a2;
 var third = a4;
 var fourth = a6;
 var line = string.Format("{0}{1}{2}{3}", first, second, third, fourth);
 stream.WriteLine(line);

I get this result: enter image description here

I need this: enter image description here

Maybe someone know how to do it?

EDIT: If I use commas, I get: enter image description here

DONE: I found my mistake, I need to add between columns a semicolons and I get what I need:

var line = string.Format("{0};{1};{2};{3}", first, second, third, fourth);
LTU
  • 195
  • 1
  • 3
  • 18
  • 2
    I never dared to manually output CSV. Too many traps to get stuck in. Better use a library to export CSV. – Uwe Keim Oct 19 '15 at 19:38
  • It depends on how you import your file in Excel. If you tell excel import to separate with ',' you code should work. – Anders Finn Jørgensen Oct 19 '15 at 19:38
  • 1
    Possible duplicate of [Writing data into CSV file](http://stackoverflow.com/questions/18757097/writing-data-into-csv-file) – Uwe Keim Oct 19 '15 at 19:39
  • Don't write CSV data yourself. You're bound to run into encoding trouble. What if the input contains commas or quotation marks or newlines? Use a library. – CodeCaster Oct 19 '15 at 19:40
  • 1
    Well that's the point, library advice is off-topic for SO. However, the de facto CSV library is called "FileHelpers". – CodeCaster Oct 19 '15 at 19:49
  • 1
    http://www.filehelpers.net/example/QuickStart/WriteFileDelimited/ – Uwe Keim Oct 19 '15 at 19:56

1 Answers1

0
var line = string.Format("{0}{1}{2}{3}", first, second, third,
fourth);

has no delimiter. Try something like this:

var line = string.Format("{0},{1},{2},{3}", first, second, third, fourth);

CSV usually stands for "Comma Separated Values" where the idea is to use that punctuation mark as a delimiter so one knows what data is which column.


Other common delimiters would be semi-colons for another idea if you want to keep that existing code.

If you want an Excel output, consider the code at http://csharp.net-informations.com/excel/csharp-format-excel.htm which uses an Interop to interpret the data better. A portion of there code is:

        xlApp = new Excel.Application();
        xlWorkBook = xlApp.Workbooks.Add(misValue);
        xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

        //add data 
        xlWorkSheet.Cells[4, 2] = "";
        xlWorkSheet.Cells[4, 3] = "Student1";
        xlWorkSheet.Cells[4, 4] = "Student2";
        xlWorkSheet.Cells[4, 5] = "Student3";
JB King
  • 11,860
  • 4
  • 38
  • 49