2015-10-19 31 views
-1

我搜索如何通過使用c#將數據輸出到csv文件,在csv我需要4列,但現在所有數據都寫入一列。我迄今所做的是:將數據輸出到一個CSV文件

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); 

我得到這樣的結果: enter image description here

我需要這樣的: enter image description here

也許有人知道該怎麼做呢?

編輯: 如果我使用逗號,我得到: enter image description here

DONE: 我發現我的錯誤,我需要列之間添加一個分號,我得到我所需要的:

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

我從來不敢手動輸出CSV。陷入太多的陷阱。更好地使用庫來導出CSV。 –

+0

這取決於您如何在Excel中導入文件。如果你告訴excel導入與','分開你的代碼應該工作。 –

+1

[將數據寫入CSV文件]可能存在重複(http://stackoverflow.com/questions/18757097/writing-data-into-csv-file) –

回答

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

沒有分隔符。嘗試是這樣的:

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

CSV通常代表「逗號分隔值」裏的想法是使用標點符號作爲分隔符所以一知道什麼數據是列。


如果您想保留現有的代碼,其他常用分隔符就是另一個想法的分號。

如果您需要Excel輸出,請考慮使用Interop來更好地解釋數據的代碼 http://csharp.net-informations.com/excel/csharp-format-excel.htm。有一部分代碼是:

 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"; 
+2

_CSV通常代表「逗號分隔值」_這就是答案。 +1。 – ryanyuyu

+0

我編輯我的文章,我會顯示如果我添加逗號會發生什麼 – LTU

+0

你能更新你使用的代碼嗎? –