Monday, January 30, 2012

How to write data to a CSV file?


The article shows the work of parsing the rows from the dataset into a file stream using a comma delimiter. By loading the data into a dataset, you have access to metadata for the columns. You can retrieve the column name from the metadata when building the row headers for your export file. If the Overwrite parameter is true, then the file will be recreated: otherwise, the data will be appended to the existing file.

public static void CreateCSVFile(DataSet myDs,String FullFilePath, Boolean Overwrite)
{
int i = 0;
int fldCnt = 0;
StreamWriter sw = new StreamWriter(FullFilePath, Overwrite);
fldCnt = myDs.Tables[0].Columns.Count;
//Gather and create csv line for columns
for (int x = 0; x <= fldCnt - 1; x++)
{
sw.Write(“[“ + myDs.Tables[0].Columns[x].ColumnName + “]”);
if (x < fldCnt - 1)
sw.Write(“,”);
}
sw.Write(sw.NewLine);
//Then gather row information into an HTML string
for (int x = 0; x <= myDs.Tables[“TABLE”].Rows.Count - 1; x++)
{
while (i < fldCnt)
{
if (!Convert.IsDBNull(myDs.Tables[“TABLE”].Rows[x][i]))
{
sw.Write(Convert.ToString(myDs.Tables[“TABLE”].Rows[x][i]));
}
if (i < fldCnt - 1)
sw.Write(“,”);
i++;
}
i = 0;
sw.Write(sw.NewLine);
}
sw.Close();
}