I. Writing the DataTable contents to a CSV file
<summary>
Save data from a DataTable to a CSV file
</summary>
private void Btnsavecsv_click (object sender, EventArgs e)
{
Savefiledialog1.filter = "CSV file |*. CSV ";
Savefiledialog1.initialdirectory = "c:\\";
if (savefiledialog1.showdialog () = = DialogResult.Cancel)
{
Return
}
Else
{
string fileName = Savefiledialog1.filename;
Savecsv (ds. Tables[0], fileName);
}
}
//<summary>
/ Writes data from a DataTable to a CSV file
//</summary>
//<param name= "DT" > provides datatable</param> to save data;
//<param name= "filename" >csv file path </param>
public void Savecsv (DataTable dt, string fileName)
{
FileStream fs = new FileStream (FileName, System.IO.FileMode.Create, System.IO.FileAccess.Write);
StreamWriter sw = new StreamWriter (FS, System.Text.Encoding.Default);
String data = "";
Write out the column name
for (int i = 0; i < dt. Columns.count; i++)
{
Data + = dt. Columns[i]. Columnname.tostring ();
if (i < dt. COLUMNS.COUNT-1)
{
Data + = ",";
}
}
Sw. WriteLine (data);
Write each row of data
for (int i = 0; i < dt. Rows.Count; i++)
{
data = "";
for (int j = 0; j < dt. Columns.count; J + +)
{
Data + = dt. ROWS[I][J]. ToString ();
if (J < dt. COLUMNS.COUNT-1)
{
Data + = ",";
}
}
Sw. WriteLine (data);
}
Sw. Close ();
Fs. Close ();
MessageBox.Show ("CSV file saved successfully! ");
}
Ii. reading the contents of the CSV file into a DataTable
<summary>
Open CSV and display its data
</summary>
private void Btnopencsv_click (object sender, EventArgs e)
{
Openfiledialog1.filter = "CSV file |*. CSV ";
if (openfiledialog1.showdialog () = = DialogResult.Cancel)
{
Return
}
Else
{
This.dgvShow.DataSource = null;
string fileName = Openfiledialog1.filename;
This.dgvShow.DataSource = Opencsv (fileName);
MessageBox.Show ("CSV data is displayed successfully! ");
}
}
<summary>
Reading data from a CSV file into a DataTable
</summary>
<param name= "fileName" >csv file path </param>
<returns> returns the datatable</returns> that read the CSV data
Public DataTable opencsv (string fileName)
{
DataTable dt = new DataTable ();
FileStream fs = new FileStream (FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
StreamReader sr = new StreamReader (FS, System.Text.Encoding.Default);
Record a row of records per read
String strLine = "";
Record the contents of each field in each row of records
String[] Aryline;
Number of marked columns
int columnCount = 0;
Indicates if the first line is read
bool IsFirst = true;
Read data in CSV row by line
while (StrLine = Sr. ReadLine ()) = null)
{
Aryline=strline.split (', ');
if (IsFirst = = True)
{
IsFirst = false;
ColumnCount = Aryline.length;
Create columns
for (int i = 0; i < ColumnCount; i++)
{
DataColumn dc = new DataColumn (Aryline[i]);
Dt. Columns.Add (DC);
}
}
Else
{
DataRow dr = dt. NewRow ();
for (int j = 0; J < ColumnCount; J + +)
{
DR[J] = Aryline[j];
}
Dt. Rows.Add (DR);
}
}
Sr. Close ();
Fs. Close ();
return DT;
}
DataTable to CSV and CSV to DataTable