C# 將DataTable數據寫入到txt文件中

見代碼:編碼

        /// <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();
            }
        }
相關文章
相關標籤/搜索