Previously, I wrote a code for Importing any CSV file into a Datagrid, now here is the code for exporting the Datagrid into the CSV file. You can load the CSV file by the code in the previous post, then that grid can be exported back to the CSV file with different name.. Here is the code for it.
This is for saving the CSV file on the particular location
SaveFileDialog sfd = new SaveFileDialog();
String stringFile = string.Empty;
if (sfd.ShowDialog() == DialogResult.OK)
{
stringFile = sf.FileName;
}
else
{
return;
}
StreamWriter streamWriter= new StreamWriter(stringFile, true);
Here I initialized datatable n merge it with the datagrid.
DataTable dt = new DataTable();
dt.Merge((DataTable)gvData.DataSource); gvData is the DataGrid name
For Columns, write function will write the columns after counting.
int iColCount = dt.Columns.Count;
for (int i = 0; i < iColCount; i++)
{
streamWriter.Write(dt.Columns[i]);
if (i < iColCount - 1)
{
streamWriter.Write(",");
}
}
streamWriter.Write(streamWriter.NewLine);
Now write all the rows.
foreach (DataRow dr in dt.Rows)
{
for (int i = 0; i < iColCount; i++)
{
if (!Convert.IsDBNull(dr[i]))
{
streamWriter.Write(dr[i].ToString());
}
if (i < iColCount - 1)
{
streamWriter.Write(",");
}
}
streamWriter.Write(streamWriter.NewLine);
}
streamWriter.Close();
Feel free to ask questions and reports problem in the C# code
Tuesday, March 9, 2010
Subscribe to:
Post Comments (Atom)

No comments:
Post a Comment