2014-07-16 37 views
0

我導出DataTable行爲CSV文件格式應該是像value,value2,value3等,但我的輸出文件顯示像這樣的值「Value」,「value2」,「value3」 這裏是我的示例代碼Exportingm DataTable csv

Utilities.WriteDataTable(TempTable, writer, true); 
public static void WriteDataTable(DataTable sourceTable, TextWriter writer, bool includeHeaders) 
    { 
     //Checking if Table has headers : 
     if (includeHeaders) 
     { 
      //Getting Headers: 
      List<string> headerValues = new List<string>(); 
      foreach (DataColumn column in sourceTable.Columns) 
      { 
       headerValues.Add(QuoteValue(column.ColumnName)); 
      } 

      writer.WriteLine(String.Join(",", headerValues.ToArray())); 
     } 
     //fetching rows from DataTable and Putting it in Array 
     string[] items = null; 
     foreach (DataRow row in sourceTable.Rows) 
     { 
      items = row.ItemArray.Select(o => QuoteValue(o.ToString())).ToArray(); 
      writer.WriteLine(String.Join(",", items)); 
     } 

     writer.Flush(); 

    } 
+0

它看起來您正在調用一個名爲'QuoteValue'的方法來創建您的項目列表。顯然這不是你的代碼。要創建一個適當的CSV,你需要報價。如果數據中有逗號,會怎麼樣? – paqogomez

回答

1

這是因爲你周圍的值加引號:沒有QuoteValue呼叫

List<string> headerValues = new List<string>(); 
foreach (DataColumn column in sourceTable.Columns) 
{ 
    headerValues.Add(QuoteValue(column.ColumnName)); 
} 

嘗試:

List<string> headerValues = new List<string>(); 
foreach (DataColumn column in sourceTable.Columns) 
{ 
    headerValues.Add(column.ColumnName); 
} 

然而,這種解決方案並非完美的解決方案,因爲應引用一些值,您應該嘗試使用第三方CSV編寫器來處理所有情況。 (見本SO回答更多細節Good CSV Writer for C#?

+0

完美的它爲我工作謝謝你的確 – Dev

0

QuoteValue是用引號括起來的值的自定義方法和加倍發現的任何報價:

private static string QuoteValue(string value) 
    { 
     return String.Concat("\"", value.Replace("\"", "\"\""), "\""); 
    } 

這有助於CSV解析器,這樣額外的列不創建:

CSV file: "one", "t,wo", "thr""ee" 
C# Array: { "one", "t,wo", "thr\"ee" } 

這會發生沒有報價處理:

CSV file: one, t,wo, thr"ee 
C# Array: { "one", "t", "wo", "thr", "ee" }