Export two list to CSV fileIn this article we will export two list data to csv file.
First we will create two classes first: Person.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ExportPerson
{
public class Person
{
public string Name { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
}
}
Second Class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ExportPersonDetail
{
public class PersonDetail
{
public string Address { get; set; }
public string Education { get; set; }
public int children { get; set; }
public string Sex { get; set; }
}
}
To convert the data of these two class to csv file . We will follow the below approach:
1) First take two list and convert both list to data table
2) Add both the datatable to dataset
3) Export dataset to csv file.
Step1:
Now we right a static class which we will use to convert list to datatable.
List Persons = new List();
DataTable dtPerson = new DataTable("Persons");
Persons.Add(new Person { Name = "Gaurav", LastName = "Gupta", Age = 28 });
List PersonDetails = new List();
DataTable dtPersonDetail = new DataTable("PersonDetails");
PersonDetails.Add(new PersonDetail { Address = "Delhi", children = 1, Education = "B.Tech", Sex = "Male" });
\\Convert List to Datatable
dtPerson = ConvertToDataTable.ToDataTable(Persons);
dtPersonDetail = ConvertToDataTable.ToDataTable(PersonDetails);
We will use one static class to convert the list to datatable the code will be as below:
public static class ConvertToDataTable
{
public static DataTable ToDataTable(this IList data)
{
PropertyDescriptorCollection props =
TypeDescriptor.GetProperties(typeof(T));
DataTable table = new DataTable();
for (int i = 0; i < props.Count; i++)
{
PropertyDescriptor prop = props[i];
table.Columns.Add(prop.Name, prop.PropertyType);
}
object[] values = new object[props.Count];
foreach (T item in data)
{
for (int i = 0; i < values.Length; i++)
{
values[i] = props[i].GetValue(item);
}
table.Rows.Add(values);
}
return table;
}
}
Step2:
Add both datatable to dataset:
DataSet ds = new DataSet();
ds.Tables.Add(dtPerson);
ds.Tables.Add(dtPersonDetail);
Now Convert dataset to csv file .
public void CreateCSVFile(DataSet ds, string strFilePath)
{
try
{
StreamWriter sw = new StreamWriter(strFilePath, false);
for (int j = 0; j < ds.Tables.Count; j++)
{
int columnCount = ds.Tables[j].Columns.Count;
for (int i = 0; i < columnCount; i++)
{
sw.Write(ds.Tables[j].Columns[i]);
if (i < columnCount - 1)
{
sw.Write(",");
}
}
sw.Write(sw.NewLine);
foreach (DataRow dr in ds.Tables[j].Rows)
{
for (int i = 0; i < columnCount; i++)
{
if (!Convert.IsDBNull(dr[i]))
{
sw.Write(dr[i].ToString());
}
if (i < columnCount - 1)
{
sw.Write(",");
}
}
sw.Write(sw.NewLine);
}
}
sw.Close();
}
catch (Exception ex)
{
throw ex;
}
}
So the final code will be like:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using ExportPerson;
using ExportPersonDetail;
using System.Data;
using System.ComponentModel;
using System.IO;
namespace ExportToCSV
{
///
/// Interaction logic for MainWindow.xaml
///
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
ExportEntity();
}
public void ExportEntity()
{
string strFile = "";
DataSet ds = new DataSet();
List Persons = new List();
DataTable dtPerson = new DataTable("Persons");
Persons.Add(new Person { Name = "Gaurav", LastName = "Gupta", Age = 28 });
dtPerson = ConvertToDataTable.ToDataTable(Persons);
List PersonDetails = new List();
DataTable dtPersonDetail = new DataTable("PersonDetails");
PersonDetails.Add(new PersonDetail { Address = "Delhi", children = 1, Education = "B.Tech", Sex = "Male" });
dtPersonDetail = ConvertToDataTable.ToDataTable(PersonDetails);
ds.Tables.Add(dtPerson);
ds.Tables.Add(dtPersonDetail);
strFile = @"C:\myCSVfile\myCSVfile.csv";
CreateCSVFile(ds, strFile);
}
public void CreateCSVFile(DataSet ds, string strFilePath)
{
try
{
StreamWriter sw = new StreamWriter(strFilePath, false);
for (int j = 0; j < ds.Tables.Count; j++)
{
int columnCount = ds.Tables[j].Columns.Count;
for (int i = 0; i < columnCount; i++)
{
sw.Write(ds.Tables[j].Columns[i]);
if (i < columnCount - 1)
{
sw.Write(",");
}
}
sw.Write(sw.NewLine);
foreach (DataRow dr in ds.Tables[j].Rows)
{
for (int i = 0; i < columnCount; i++)
{
if (!Convert.IsDBNull(dr[i]))
{
sw.Write(dr[i].ToString());
}
if (i < columnCount - 1)
{
sw.Write(",");
}
}
sw.Write(sw.NewLine);
}
}
sw.Close();
}
catch (Exception ex)
{
throw ex;
}
}
}
public static class ConvertToDataTable
{
public static DataTable ToDataTable(this IList data)
{
PropertyDescriptorCollection props =
TypeDescriptor.GetProperties(typeof(T));
DataTable table = new DataTable();
for (int i = 0; i < props.Count; i++)
{
PropertyDescriptor prop = props[i];
table.Columns.Add(prop.Name, prop.PropertyType);
}
object[] values = new object[props.Count];
foreach (T item in data)
{
for (int i = 0; i < values.Length; i++)
{
values[i] = props[i].GetValue(item);
}
table.Rows.Add(values);
}
return table;
}
}
}
and the output will be like the below image: