/// <summary>
/// datatable数据列全转换为字符串
/// </summary>
/// <param name="sourceTable"></param>
/// <returns></returns>
public static DataTable ConvertDataColumType(DataTable sourceTable)
{
//克隆表结构
DataTable dtResult = sourceTable.Clone();
List<string> lsCol = GetDateTimeColName(ref dtResult);
foreach (DataRow row in sourceTable.Rows)
{
DataRow rowNew = dtResult.NewRow();
foreach (DataColumn itemCol in dtResult.Columns)
{
if (!lsCol.Contains(itemCol.ColumnName))
{
rowNew[itemCol] = row[itemCol.ColumnName];
}
else
{
string sColValue = !row.IsNull(itemCol.ColumnName)
? DateTime.Parse(row[itemCol.ColumnName].ToString()).ToString("yyyy-MM-dd HH:mm:ss")
: "";
rowNew[itemCol] = sColValue;
}
}
dtResult.Rows.Add(rowNew);
}
return dtResult;
}
public static List<string> GetDateTimeColName(ref DataTable dtResult)
{
List<string> lsCol = new List<string>();
foreach (DataColumn col in dtResult.Columns)
{
if (col.DataType == typeof (System.DateTime)
&& !lsCol.Contains(col.ColumnName))
{
lsCol.Add(col.ColumnName);
}
//修改列类型
col.DataType = typeof(string);
}
return lsCol;
}