Datatable to CSV file

C# DataTable to a CSV file
C# DataTable to a CSV file with default options i.e. all columns with default column names


public static string DataTableToCsvFile(DataTable TableData, string FileName)
{
	try
	{
		// change this with any delimiter you want
		string Delimiter = ",";
		int i = 0;
		StreamWriter sw = null;

		sw = new StreamWriter(FileName, false);

		List<int> mIndexes = new List<int>();

		for (i = 0; i < TableData.Columns.Count; i++)
		{
			sw.Write("\"" + TableData.Columns[i].ColumnName + "\"" + Delimiter);
		}

		sw.WriteLine();

		foreach (DataRow row in TableData.Rows)
		{
			object[] array = row.ItemArray;

			//for (i = 0; i < array.Length; i++)
			foreach (int mIndex in mIndexes)
			{
				sw.Write("\"" + array[mIndex].ToString() + "\"" + Delimiter);
			}

			sw.WriteLine();
		}

		sw.Flush();
		sw.Close();

		return FileName;
	}
	catch (Exception exp)
	{
		throw exp;
	}
}

C# DataTable to a CSV file Custom
C# DataTable to a CSV file with custom options like Custom headers and Selected fields. “Format” in parameters will contain comma separated values like column1=column 1 name, column2=column 2 name and so on


public static string DataTableToCsvFile(DataTable TableData, string FileName, string Format)
{
	try
	{

		Dictionary<string, string> mFormatDictionary = CSVtoDictionary(Format);

		// change this with any delimiter you want
		string Delimiter = ",";
		int i = 0;
		StreamWriter sw = null;
		 
		sw = new StreamWriter(FileName, false);

		List<int> mIndexes = new List<int>();

		for (i = 0; i < TableData.Columns.Count; i++)
		{
			if (Format.Contains(TableData.Columns[i].ColumnName))
			{
				mIndexes.Add(i);
				sw.Write("\"" + mFormatDictionary[TableData.Columns[i].ColumnName] + "\"" + Delimiter);
			}
		}
		
		sw.WriteLine();

		foreach (DataRow row in TableData.Rows)
		{
			object[] array = row.ItemArray;

			//for (i = 0; i < array.Length; i++)
			foreach(int mIndex in mIndexes)
			{
				sw.Write("\"" + array[mIndex].ToString() + "\"" + Delimiter);
			}
			
			sw.WriteLine();
		}

		sw.Flush();
		sw.Close();

		return FileName;
	}
	catch (Exception exp)
	{
		throw exp;
	}
}

To get Dictionary of Key Value pair for the format string (utility function used in above code)


public static Dictionary<string, string> CSVtoDictionary(string Format)
{
	string[] mFormatArray = Format.Split(new char[] { ',' });
	Dictionary<string, string> mKVPair = new Dictionary<string, string>(mFormatArray.Length);

	foreach (string mFormatArrayItem in mFormatArray)
	{
		string[] mPair = mFormatArrayItem.Split(new char[] { '=' });
		mKVPair.Add(mPair[0], mPair[1]);
	}

	return mKVPair;
}

Leave a Reply

Your email address will not be published.