/// <summary>
/// datatable生成CSV字符串
/// </summary>
/// <param name="dt"></param>
/// <param name="hasTitle"></param>
/// <returns></returns>
public static string DataTableToCsv(DataTable dt,bool hasTitle=false)
{
StringBuilder sb = new StringBuilder();
DataColumn column;
if (hasTitle)
{
for (int i = 0; i < dt.Columns.Count; i++)
{
if (0 != i) sb.Append(",");
sb.Append(dt.Columns[i].ColumnName);
}
sb.AppendLine();
}
foreach (DataRow row in dt.Rows)
{
for (int i = 0; i < dt.Columns.Count; i++)
{
column = dt.Columns[i];
if (0 != i) sb.Append(",");
// 如包含逗号 则需双引号包含
if (column.DataType == typeof(string) && row[column].ToString().Contains(","))
{
//如包含双引号 则需用两个双引号替换
sb.Append("\"" + row[column].ToString().Replace("\"", "\"\"") + "\"");
}
else
sb.Append(row[column].ToString());
}
sb.AppendLine();
}
return sb.ToString();
}