Skip to content

Instantly share code, notes, and snippets.

@gopigujjula

gopigujjula/DataTableToCsv

Last active Feb 27, 2020
Embed
What would you like to do?
Conversion from DataTable to Csv file in C#.
using System;
using System.Text;
using System.Data;
using System.IO;
namespace Conversion
{
class DataConvert
{
static void Main(string[] args)
{
//converting DataTable to Csv file.
DataTableToCsv obj = new DataTableToCsv();
DataTable dtData = obj.CreateStudentTableSchema();
dtData = obj.FillData(dtData);
StringBuilder data = obj.ConvertDataTableToCsvFile(dtData);
obj.SaveData(data, @"D:\\student.csv");
Console.WriteLine("Data converted successfully from DataTable to Csv file.");
Console.ReadLine();
}
}
class DataTableToCsv
{
//This method creates the DataTable schema (column names and their types).
public DataTable CreateStudentTableSchema()
{
DataTable dtData = new DataTable("Student");
dtData.Columns.Add("StudentId", typeof(int));
dtData.Columns.Add("Name", typeof(string));
dtData.Columns.Add("Course", typeof(string));
dtData.Columns.Add("Age", typeof(int));
return dtData;
}
//This method fill the data table with some sample records.
public DataTable FillData(DataTable dtData)
{
dtData.Rows.Add(1, "Bala", "MCA", 26);
dtData.Rows.Add(2, "Murali", "BCA", 23);
dtData.Rows.Add(3, "Venu", "BSC", 23);
dtData.Rows.Add(4, "Srinivas", "BBM", 22);
dtData.Rows.Add(5, "Srikanth", "MBA", 25);
dtData.Rows.Add(6, "Harsha", "MCA", 26);
return dtData;
}
//This method convertrs the DataTable to Csv (in the form of StringBuilder instance).
public StringBuilder ConvertDataTableToCsvFile(DataTable dtData)
{
StringBuilder data = new StringBuilder();
//Taking the column names.
for (int column = 0; column < dtData.Columns.Count; column++)
{
//Making sure that end of the line, shoould not have comma delimiter.
if (column == dtData.Columns.Count - 1)
data.Append(dtData.Columns[column].ColumnName.ToString().Replace(",", ";"));
else
data.Append(dtData.Columns[column].ColumnName.ToString().Replace(",", ";") + ',');
}
data.Append(Environment.NewLine);//New line after appending columns.
for (int row = 0; row < dtData.Rows.Count; row++)
{
for (int column = 0; column < dtData.Columns.Count; column++)
{
////Making sure that end of the line, shoould not have comma delimiter.
if (column == dtData.Columns.Count - 1)
data.Append(dtData.Rows[row][column].ToString().Replace(",", ";"));
else
data.Append(dtData.Rows[row][column].ToString().Replace(",", ";") + ',');
}
//Making sure that end of the file, should not have a new line.
if (row != dtData.Rows.Count - 1)
data.Append(Environment.NewLine);
}
return data;
}
//This method saves the data to the csv file.
public void SaveData(StringBuilder data, string filePath)
{
using (StreamWriter objWriter = new StreamWriter(filePath))
{
objWriter.WriteLine(data);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.