Created
December 27, 2012 05:15
-
-
Save ledsun/4385662 to your computer and use it in GitHub Desktop.
DataTableをCSV文字列に変換する拡張メソッド
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Data; | |
using System.Linq; | |
using System.Text; | |
namespace Ledsun | |
{ | |
public static class DataTableExtentions | |
{ | |
#region 抽出結果データテーブルをCSVテキストに変換する。 | |
/// <summary> | |
/// データテーブル→CSV変換 | |
/// </summary> | |
/// <param name="dataTable">結果データテーブル</param> | |
/// <param name="headerLines">CSV部分の前に記述するテキスト</param> | |
/// <returns>CSV化した文字列</returns> | |
public static string ToCsv(this DataTable dataTable, string headerLines = "") | |
{ | |
var retCSV = new StringBuilder(); | |
retCSV.AddHeader(headerLines); | |
//データテーブル、カンマ区切りテキスト化 | |
//列名行 | |
var columnNameLine = string.Join( | |
",", | |
dataTable | |
.Columns | |
.Cast<DataColumn>() | |
.Select(c => c.Caption) | |
.Select(field => FormatForCsv(field)) | |
); | |
retCSV.AppendLine(columnNameLine); | |
//データ行 | |
foreach (DataRow row in dataTable.Rows) | |
{ | |
var dataLine = string.Join( | |
",", | |
row | |
.ItemArray | |
.Select(i => i.ToString()) | |
.Select(field => FormatForCsv(field)) | |
); | |
retCSV.AppendLine(dataLine); | |
} | |
return retCSV.ToString(); | |
} | |
/// <summary> | |
/// ヘッダを追加します。 | |
/// </summary> | |
/// <param name="retCSV"></param> | |
/// <param name="headerLines"></param> | |
private static void AddHeader(this StringBuilder retCSV, string headerLines) | |
{ | |
if (headerLines.Length > 0) | |
{ | |
retCSV.AppendLine(headerLines); | |
retCSV.AppendLine(""); | |
}; | |
} | |
/// <summary> | |
/// CSVのカラムフォーマット | |
/// </summary> | |
/// <param name="field"></param> | |
/// <returns></returns> | |
private static string FormatForCsv(string field) | |
{ | |
// "で囲む必要があるか調べる | |
if (field.Contains('"') | |
|| field.Contains(',') | |
|| field.Contains('\r') | |
|| field.Contains('\n') | |
|| field.StartsWith(" ") | |
|| field.StartsWith("\t") | |
|| field.EndsWith(" ") | |
|| field.EndsWith("\t")) | |
{ | |
if (field.Contains('"')) | |
{ | |
//"を""とする | |
field = field.Replace("\"", "\"\""); | |
} | |
field = "\"" + field + "\""; | |
} | |
return field; | |
} | |
#endregion | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
http://d.hatena.ne.jp/JHashimoto/20120223/1330000075