Exemplo n.º 1
0
        /// <summary>
        /// Writes a datatable as a CSV string and returns the string
        /// </summary>
        /// <param name="dataTable">The data source</param>
        /// <returns>A CSV representation of the data table</returns>
        /// <param name="settings">Optional csv settings</param>
        public static string ToCsv(this DataTable dataTable, ToCsvSettings settings = null)
        {
            Contract.Requires(dataTable != null);

            StringBuilder fileContent = new StringBuilder();

            bool firstLine = true;

            settings = settings ?? new ToCsvSettings();

            if (settings.IncludeHeaders)
            {
                fileContent.Append(string.Join(",", dataTable.Columns.Cast <DataColumn>())); //ToString for the header name?
                firstLine = false;
            }

            foreach (DataRow dr in dataTable.Rows)
            {
                if (!firstLine)
                {
                    fileContent.Append(System.Environment.NewLine);
                }

                fileContent.Append(dr.ToCsvRow(settings.QuoteCharacter));

                firstLine = false;
            }

            return(fileContent.ToString());
        }
Exemplo n.º 2
0
        /// <summary>
        /// Writes a DataTable to a CSV file specified by the path
        /// </summary>
        /// <param name="dataTable">The datatable to write</param>
        /// <param name="filePath">The location of the CSV to create</param>
        /// <param name="settings">Optional csv settings</param>
        public static void ToCsv(this DataTable dataTable, string filePath, ToCsvSettings settings = null)
        {
            settings = settings ?? new ToCsvSettings();

            using (IFileWriter fileWriter = FileWriterFactory.GetFileWriter(filePath, settings.Compression))
            {
                fileWriter.Write(dataTable.ToCsv(settings));
            }
        }