C# 将DataTable数据写入到txt文件中

时间:2022-11-06 11:37:43

见代码:

        /// <summary>
        /// 将DataTable里面的内容写入txt文件
        /// </summary>
        /// <param name="dt">数据表</param>
        /// <param name="columnNames">要写的字段列表</param>
        /// <param name="fileName">文件名,全路径,建议以.txt为后缀</param>
        /// <param name="encoding">文件编码格式</param>
        /// <param name="fieldsTerminated">字段分隔符,默认为\t制表符</param>
        /// <returns></returns>
        public void WriteDataTableIntoFile(DataTable dt, List<string> columnNames, string fileName, Encoding encoding, string fieldsTerminated = "\t")
        {
            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('\t', ' ').Replace('\r', ' ').Replace('\n', ' '));
                        }
                        col++;
                    }
                    streamWriter.WriteLine();
                    streamWriter.Flush();
                }
                streamWriter.Close();
                streamWriter.Dispose();
            }
        }