见代码:
/// <summary> /// 将DataTable里面的内容写入txt文件 /// </summary> /// <param name="dt">数据表</param> /// <param name="columnNames">要写的字段列表</param> /// <param name="fileName">文件名,全路径,建议以.txt为后缀</param> /// <param name="encoding">文件编码格式</param> /// <param name="fieldsTerminated">字段分隔符,默认为 制表符</param> /// <returns></returns> public void WriteDataTableIntoFile(DataTable dt, List<string> columnNames, string fileName, Encoding encoding, string fieldsTerminated = " ") { if (dt == null) { return; } //写数据文件 using (StreamWriter streamWriter = new StreamWriter(fileName, false, encoding)) { int col = 0; foreach (DataRow dr in dt.Rows) { col = 0; foreach (string column in columnNames) { if (col > 0) { streamWriter.Write(fieldsTerminated); } if (dt.Columns[column].DataType == typeof(DateTime)) { if (dr[column] == DBNull.Value) { //streamWriter.Write("0000-00-00 00:00:00"); } else { streamWriter.Write(((DateTime)dr[column]).ToString("yyyy-MM-dd HH:mm:ss")); } } else { streamWriter.Write(Convert.ToString(dr[column]).Replace(' ', ' ').Replace(' ', ' ').Replace(' ', ' ')); } col++; } streamWriter.WriteLine(); streamWriter.Flush(); } streamWriter.Close(); streamWriter.Dispose(); } }