Sunday, March 21, 2010

C# - save content to CSV file from GridView

Below is an example to save content from GridView to CSV file:

{
....
string strPath = ".\\XXX_" + strFName + ".csv";
if (File.Exists(strPath))
{
File.Delete(strPath);
}

StringBuilder strColu = new StringBuilder();
StringBuilder strValue = new StringBuilder();
int i = 0;
int j = 0;

try
{
StreamWriter sw = new StreamWriter(new FileStream(strPath,
FileMode.CreateNew), Encoding.GetEncoding("GB2312"));
// ----------------------------------------------------------------
// Write header to CSV file
// ----------------------------------------------------------------
for (i = 0; i <= iTotalCol; i++)
{
strColu.Append(GridView_Task.Columns[i].HeaderText);
strColu.Append(",");
}
strColu.Remove(strColu.Length - 1, 1); // remove last character
sw.WriteLine(strColu);

// ----------------------------------------------------------------
// Write content to CSV file
// ----------------------------------------------------------------
for (i = 0; i < iTotalRow; i++)
{
strValue.Remove(0, strValue.Length);
DataGridViewRow dr = GridView_Task.Rows[i];

for (j = 0; j <= iTotalCol; j++)
{
strValue.Append(dr.Cells[j].Value.ToString());
strValue.Append(",");
}
strValue.Remove(strValue.Length - 1, 1); // remove last character
sw.WriteLine(strValue);
}
sw.Close();

MessageBox.Show("OK. Success to generate CSV file.");
}
catch (Exception ex)
{
MessageBox.Show("Fail to generate CSV file. Error=[" + ex.Message + "]");
}
...
}

No comments: