Exporting Grid Controls's data to Comma Separated Values

Most of the times , we end up writing different helper classes to export grids to various formats.

One such most common file format that clients require is Comma delimited Values. Below helper class shows how to do this in a simple way.

 

Necessary comments are marked in red.

 

#region Namespaces

 

using System;

using System.IO;

using System.Data;

using System.Text;

 

#endregion Namespaces

 

namespace Utilities

{

    /// <summary>

    /// Exporter Class to CSV.

    /// </summary>

    public sealed class CSVExporter

    {

 

        /// <summary>

        /// Exports the data set to CSV.

        /// </summary>

        /// <param name="ds">The ds.</param>

        /// <param name="filename">The filename.</param>

       public static void ExportDataSetToCSV(DataSet ds, string filename)

        {

            using (StreamWriter sw = new StreamWriter(filename, false, Encoding.Default))

            {

                //write column headers

                foreach (DataColumn dc in ds.Tables[0].Columns)

                    sw.Write(dc.Caption.ToString() + ",");

 

                sw.Write(sw.NewLine);

 

                //write column data

                foreach (DataTable dt in ds.Tables)

                {

                    foreach (DataRow dr in dt.Rows)

                    {

                        for (int i = 0; i < dt.Columns.Count; i++)

                        {

                            if (!Convert.IsDBNull(dr[i]))

                                sw.Write(string.Format("\"{0}\",", dr[i]));

                            else

                                sw.Write("\"\",");

                        }

                        sw.Write(sw.NewLine);

                    }

                }

                sw.Flush();

                sw.Close();

            }

        }

 

        /// <summary>

        /// Writes the data.

        /// </summary>

        /// <param name="sw">The sw.</param>

        /// <param name="dt">The dt.</param>

        private static void WriteData(StreamWriter sw, DataTable dt)

        {

            foreach (DataRow dr in dt.Rows)

            {

                for (int i = 0; i < dt.Columns.Count; i++)

                {

                    if (!Convert.IsDBNull(dr[i]))

                        sw.Write(string.Format("\"{0}\",", dr[i]));

                    else

                        sw.Write("\"\",");

                }

                sw.Write(sw.NewLine);

            }

        }

 

        /// <summary>

        /// Writes the data.

        /// </summary>

        /// <param name="sw">The sw.</param>

        /// <param name="dv">The dv.</param>

        /// <param name="sequenceColumnNames">The sequence column names.</param>

        private static void WriteData(StreamWriter sw, DataView dv, string[] sequenceColumnNames)

        {

            foreach (DataRowView dr in dv)

            {

                for (int columnIndex = 0; columnIndex < sequenceColumnNames.Length; columnIndex++)

                {

                    if (!Convert.IsDBNull(dr[sequenceColumnNames[columnIndex]]))

                        sw.Write(string.Format("\"{0}\",", dr[sequenceColumnNames[columnIndex]]));

                    else

                        sw.Write("\"\",");

                }

                sw.Write(sw.NewLine);

            }

        }

 

      

    }

}


Create a button called btnCSVExporter and in its click event write the following code.

 

  /// <summary>

        /// Handles the Click event of the ButtonCSVExporter control.

        /// </summary>

        /// <param name="sender">The source of the event.</param>

        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>

        private void ButtonCSVExporter_Click(object sender, System.Windows.RoutedEventArgs e)

        {

            //Replace this with your own handler if you need.

            string csvDataFile = SaveDialogEx.GetFileNameForSave(FileExtenion.CSV, "Exported Grid data");

 

            if (string.IsNullOrEmpty(csvDataFile))

                return;

 

            DataSet exportDataSet = new DataSet();

 

            if(xdg.DataSource is DataSet)

            {

                exportDataSet = (xdg.DataSource as DataSet);

            }

 

            if (xdg.DataSource is DataView)

            {

                exportDataSet = (xdg.DataSource as DataView).Table.DataSet;

            }

 

            CSVExporter. ExportDataSetToCSV (exportDataSet, csvDataFile);

        }

 
Cheers

By [)ia6l0 iii   Popularity  (1103 Views)