Tuesday, May 19, 2009

Export DataTable into CSV

class ExportDataToCSV
{
///
/// It will export data in DataTable into CSV format
/// and use TextWriter Object to write it.
///

///
///
///
public static void mCreateCSV(DataTable dt, System.IO.TextWriter httpStream, bool WriteHeader)
{
if(WriteHeader)
{
string[] arr = new String[dt.Columns.Count];
int k = dt.Columns.Count;
for(int i = 0; i {
arr[i] = dt.Columns[i].ColumnName;
arr[i] = GetWriteableValue(arr[i]);
}

httpStream.WriteLine(string.Join(",", arr));
}

for(int j = 0; j {
string[] dataArr = new String[dt.Columns.Count];
for(int i = 0; i {
object o = dt.Rows[j][i];
dataArr[i] = GetWriteableValue(o);
}
httpStream.WriteLine(string.Join(",", dataArr));
}
}

///
/// It will export Data in DataTable into CSV format
/// and write it using object of StreamWriter
///

///
///
///
public static void mCreateCSV(DataTable dt, System.IO.StreamWriter file, bool WriteHeader)
{
if(WriteHeader)
{
string[] arr = new String[dt.Columns.Count];
for(int i = 0; i {
arr[i] = dt.Columns[i].ColumnName;
arr[i] = GetWriteableValue(arr[i]);
}

file.WriteLine(string.Join(",", arr));
}

for(int j = 0; j {
string[] dataArr = new String[dt.Columns.Count];
for(int i = 0; i {
object o = dt.Rows[j][i];
dataArr[i] = GetWriteableValue(o);
}
file.WriteLine(string.Join(",", dataArr));
}
}

public static string GetWriteableValue(object o)
{
if(o==null || o == Convert.DBNull)
return "";
else if(o.ToString().IndexOf(",")==-1)
return o.ToString();
else
return "\"" + o.ToString() + "\"";

}

}

No comments:

Post a Comment

 
Locations of visitors to this page