Skip to content

Instantly share code, notes, and snippets.

@ledsun
Created December 27, 2012 05:15
Show Gist options
  • Save ledsun/4385662 to your computer and use it in GitHub Desktop.
Save ledsun/4385662 to your computer and use it in GitHub Desktop.
DataTableをCSV文字列に変換する拡張メソッド
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
}
}
@ledsun
Copy link
Author

ledsun commented Dec 27, 2012

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment