Friday, October 23, 2009

Function to export DataTable to csv File

public void CreateCSVFile(DataTable dt, string strFilePath)
{
try
{
// Create the CSV file to which grid data will be exported.

StreamWriter sw = new StreamWriter(strFilePath, false);

int iColCount = dt.Columns.Count;

foreach (DataRow dr in dt.Rows)
{
for (int i = 0; i < iColCount-2; i++)
{
if (!Convert.IsDBNull(dr[i]))
{
sw.Write(dr[i].ToString());
}

if (i < iColCount - 1)
{
sw.Write(",");
}

}

sw.Write(sw.NewLine);

}
sw.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}

}

No comments: