C# CSV 파일 생성 또는 내보내기

3267 단어
직접 부호
/// 
        ///   CSV
        /// 
        ///     
        ///     
        ///   
        ///    
        public static void ExportCSV(System.Data.DataTable table, string directory, string fileName)
        {
            //     

            string directoryName = directory;
            if (!Directory.Exists(directoryName))
            {
                Directory.CreateDirectory(directoryName);
            }
            string file = directory + fileName;
            // if (!this.FileExist(file))
            // {
            ExportCSV(table, file);
            //Process.Start(file);
            //  }
            //      

        }
#region public static void ExportCSV(DataTable dataTable, string fileName)   CSV    
        /// 
        ///   CSV    
        /// 
        ///    
        ///    
        public static void ExportCSV(DataTable dataTable, string fileName)
        {
            StreamWriter StreamWriter = new StreamWriter(fileName, false, System.Text.Encoding.GetEncoding("gb2312"));
            StreamWriter.WriteLine(GetCSVFormatData(dataTable).ToString());
            StreamWriter.Flush();
            StreamWriter.Close();
        }
        #endregion
#region public static StringBuilder GetCSVFormatData(DataTable dataTable)   DataTable  CSV    
        /// 
        ///   DataTable  CSV    
        /// 
        ///    
        /// CSV     
        public static StringBuilder GetCSVFormatData(DataTable dataTable)
        {
            StringBuilder StringBuilder = new StringBuilder();
            //     

            StringBuilder.Append("AAAA,VVVVV,CCCCC ");
            StringBuilder.Append("
"); // int count = 0; foreach (DataRowView dataRowView in dataTable.DefaultView) { count++; foreach (DataColumn DataColumn in dataTable.Columns) { string field = dataRowView[DataColumn.ColumnName].ToString(); if (field.IndexOf('"') >= 0) { field = field.Replace("\"", "\"\""); } field = field.Replace(" ", " "); if (field.IndexOf(',') >= 0 || field.IndexOf('"') >= 0 || field.IndexOf('= 0 || field.IndexOf('>') >= 0 || field.IndexOf("'") >= 0) { field = "\"" + field + "\""; } StringBuilder.Append(field + ","); field = string.Empty; } if (count != dataTable.Rows.Count) { StringBuilder.Append("
"); } } return StringBuilder; } #endregion

좋은 웹페이지 즐겨찾기