---
# System prepended metadata

title: '[C#]匯出 .csv'
tags: [c#, .csv, Visual Studio]

---

# [C#]匯出 .csv

###### tags: `c#` `.csv` `Visual Studio`
> [time= 2019 11 07 ] 

<br>

## 匯出
```csharp=
/// <summary>
/// 匯出 CSV
/// </summary>
/// <param name="dataTable">匯出的資料</param>
/// <param name="exportFile">匯出路徑</param>
/// <param name="encoding">文字編碼</param>      
/// <param name="wirteHead">是否輸出表頭</param>
public static void exportDataAsCsvString (DataTable dataTable, string exportFile, Encoding encoding, bool writeHead = true) {
	StringBuilder sb = new StringBuilder ();

	if (writeHead) {
		List<string> headers = new List<string> ();
		for (int i = 0; i < dataTable.Columns.Count; i++) {
			DataColumn column = dataTable.Columns[i];
			headers.Add (column.ColumnName);
		}
		sb.AppendLine (string.Join (",", headers.ToArray ()));
	}

	for (int i = 0; i < dataTable.Rows.Count; i++) {
		DataRow row = dataTable.Rows[i];
		var s = string.Join (",", row.ItemArray);
		sb.AppendLine (s.ToString ());
	}

	System.IO.File.WriteAllText (exportFile, sb.ToString (), encoding);
}
```

<br><br><br>

## 設定欄位名稱 & 排序欄位順序
* 設定欄位名稱
  
  通常要看報表的人，會希望欄位中文，所以要特別設定欄位名稱

<br>

* 排序欄位順序 & 過濾欄位
  
  C# 有時候從資料庫撈出的資料欄位排序順序不是按照 SQL 語法撈出來的樣子，甚至會多出一些系統的資訊欄位。這個時候就要去設定它的欄位順序和過濾不必要的欄位。
  
```csharp=
/// <summary>
/// 設定欄位名稱 & 排序欄位順序
/// </summary>
/// <param name="dataTable">匯出的資料</param>
/// <param name="titleColumnName">欄位順序</param>
/// <param name="setColumnName">設定爛為名稱</param>
/// <returns></returns>
public DataTable resetDataTable (DataTable dataTable, List<string> titleColumnName, List<string> setColumnName, bool wirteHead) {
	#region  預設欄位名稱
	if (wirteHead) {
		if (setColumnName.Count == 0) {
			for (int i = 0; i < titleColumnName.Count; i++) {				 
				setColumnName.Add (""); //空值，後續自動給資料庫的欄位名稱				
			}
		} else if (titleColumnName.Count > setColumnName.Count) {
			throw new Exception ("setColumnName 的欄位有缺，請與 titleColumnName 的欄位數相同。");
		}
	}
	#endregion

	#region 刪除不想要的欄位(主要是刪除 ExtensionData 欄位)
	var delColumnList = new List<string> ();

	foreach (DataColumn column in dataTable.Columns) {
		if (!titleColumnName.Contains (column.ColumnName)) {
			delColumnList.Add (column.ColumnName);
		}
	}

	foreach (var columnName in delColumnList) {
		dataTable.Columns.Remove (columnName);
	}
	#endregion

	for (int i = 0; i < titleColumnName.Count; i++) {
		//利用 ColumnName 來排序欄位順序
		dataTable.Columns[titleColumnName[i].ToString ()].SetOrdinal (i);

		//設定中文欄位
		if (wirteHead && !String.IsNullOrEmpty (setColumnName[i].ToString ())) {
			dataTable.Columns[titleColumnName[i].ToString ()].ColumnName = setColumnName[i].ToString ();
		}
	}

	return dataTable;
}
```

<br><br><br>

## 程式使用範例

```csharp=
static void Main (string[] args) {
	var showColumnName = new List<string> {
		"name",
		"email",
		"message"
	};
	var chineseColumnName = new List<string> {
		"名字",
		"mail",
		"訊息"
	};
	DataTable resultDT = "你要匯出的資料表";
	DataTable exportDatas = resetDataTable(resultDT, showColumnName, chineseColumnName, true);
    
	string exportFile =  "path/filname.csv";
	Encoding encodingType = Encoding.UTF8;
	exportDataAsCsvString(exportDatas, exportFile, encodingType, true);
}
```