Today i found myself wanting to quickly export a dataset to CSV and i didn’t want to bloat of a library that does more than i need. The following method is the result of this need/want.
private string ConvertToCSV(DataSet objDataSet) { StringBuilder content = new StringBuilder(); if (objDataSet.Tables.Count >= 1) { DataTable table = objDataSet.Tables[0]; if (table.Rows.Count > 0) { DataRow dr1 = (DataRow) table.Rows[0]; int intColumnCount = dr1.Table.Columns.Count; int index=1; //add column names foreach (DataColumn item in dr1.Table.Columns) { content.Append(String.Format("\"{0}\"", item.ColumnName)); if (index < intColumnCount) content.Append(","); else content.Append("\r\n"); index++; } //add column data foreach (DataRow currentRow in table.Rows) { string strRow = string.Empty; for (int y = 0; y <= intColumnCount - 1; y++) { strRow += "\"" + currentRow[y].ToString() + "\""; if (y < intColumnCount - 1 && y >= 0) strRow += ","; } content.Append(strRow + "\r\n"); } } } return content.ToString(); }
Things to note:
- This won’t take care of field contents which contain double quotes, you may want to add support for this
- This only exports the first table in a dataset
- Its pretty quick and nasty, so don’t blame me if you have issues