xxxxxxxxxx
/// <summary>
/// Convert DataTable to CSV
/// </summary>
/// <param name="filePath"></param>
/// <param name="table"></param>
/// <param name="fileName"></param>
/// <returns></returns>
public bool Write(string filePath, DataTable table, string fileName)
{
bool success = false;
try
{
var columns = table.Columns.Cast<DataColumn>().Select(x => x.ColumnName).ToList();
string[] columnsArray = Util_DataConversion.ConvertListToArray(columns);
sb.AppendLine(string.Join(",", columnsArray));
foreach (DataRow rw in table.Rows)
{
string[] flds = rw.ItemArray.Select(x => x.ToString()).ToArray();
sb.AppendLine(string.Join(",", flds));
}
File.WriteAllText(filePath + "\\" + fileName, sb.ToString());
success = true;
return success;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
To create a DataTable from a CSV file in C#, you can use the TextFieldParser class from the Microsoft.VisualBasic.FileIO namespace.
xxxxxxxxxx
using System.Data;
using Microsoft.VisualBasic.FileIO;
// Assuming you have a CSV file named "data.csv" with headers
string csvFilePath = "data.csv";
// Create the DataTable
DataTable dataTable = new DataTable();
// Use TextFieldParser to read the CSV file
using (TextFieldParser parser = new TextFieldParser(csvFilePath))
{
// Set parser properties
parser.TextFieldType = FieldType.Delimited;
parser.SetDelimiters(",");
// Read the headers
string[] headers = parser.ReadFields();
// Add the headers as columns to the DataTable
foreach (string header in headers)
{
dataTable.Columns.Add(header);
}
// Read the data rows
while (!parser.EndOfData)
{
// Read the fields for the current row
string[] fields = parser.ReadFields();
// Create a new DataRow and add the fields as values
DataRow dataRow = dataTable.NewRow();
for (int i = 0; i < fields.Length; i++)
{
dataRow[i] = fields[i];
}
// Add the DataRow to the DataTable
dataTable.Rows.Add(dataRow);
}
}
This code assumes that the CSV file has headers in the first row. If the file doesn't have headers, you can remove the code that reads and adds them to the DataTable.