Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR CSHARP

c# convert datatable to csv

  /// <summary>
        /// Convert DataTable to CSV
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="table"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public bool Write(string filePath, DataTable table, string fileName)
        {
            bool success = false;
            try
            {
                var columns = table.Columns.Cast<DataColumn>().Select(x => x.ColumnName).ToList();
                string[] columnsArray = Util_DataConversion.ConvertListToArray(columns);
                sb.AppendLine(string.Join(",", columnsArray));

                foreach (DataRow rw in table.Rows)
                {
                   
                    string[] flds = rw.ItemArray.Select(x => x.ToString()).ToArray();
                    sb.AppendLine(string.Join(",", flds));
                }

                File.WriteAllText(filePath + "" + fileName, sb.ToString());
                success = true;
                return success;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
 
PREVIOUS NEXT
Tagged: #convert #datatable #csv
ADD COMMENT
Topic
Name
1+9 =