Showing posts with label DataTable to .CSV file creation. Show all posts
Showing posts with label DataTable to .CSV file creation. Show all posts

Tuesday, September 10, 2013

DataTable to CSV generator

This code will generate the .csv (Comma separator file) from the Data source like DataTable or XML strings.
    protected void CreateCSV(object sender,EventArgs e)
        {
            MemoryStream ms = new MemoryStream();
            DataSet ds = new DataSet();
            ds.ReadXml(@"d:\students.xml");
            if (ds.Tables[0].Rows.Count > 0)
            {
                StreamWriter writer = new StreamWriter(ms);
                writer.AutoFlush = true;

                foreach (DataColumn column in ds.Tables[0].Columns)
                {
                    writer.Write(column.ColumnName.ToString() + ",");
                }
                writer.WriteLine();

                foreach (DataRow drow in ds.Tables[0].Rows)
                {
                      writer.Write(drow["Name"].ToString() + "," + Convert.ToDateTime(drow["DOJ"]).ToShortDateString().ToString() + "," + drow["Height"].ToString() + ",");
                      writer.WriteLine();
                }
            }
            using (FileStream file = new FileStream("D:\\file5.csv", FileMode.Create, FileAccess.Write))
            {
                
                ms.WriteTo(file);
            }
        }
Sample XML file to work on the above solution.


Murugesan
12/12/2013
155.57845645


Murugesan
12/12/2013
155.57845645


Amit Ingle
05/04/2013
155.57845645