Problem:
User wants to view data in Excel.
1) Execute query against database.
2) Build DataTable object.
3) Populate Grid Control (DataGrid, GridView...)
4) Export DataTable to CSV file
Solution:
private int Export2CSV(DataTable dt,
string sFullPathAndFileName,
bool bNeedHeaderRow)
{
//usage history initialization
this.int_error_level = 0;
this.str_last_message = string.Empty;
try
{
System.IO.StreamWriter sw = new
System.IO.StreamWriter(sFullPathAndFileName,
false,
System.Text.Encoding.ASCII,
4096);
System.Text.StringBuilder buff = new System.Text.StringBuilder();
if (bNeedHeaderRow == true)
{
//build header
for (int c = 0; c < dt.Columns.Count; c++)
{
buff.Append(dt.Columns[c].ColumnName.ToString().ToUpper());
if (c < (dt.Columns.Count - 1))
{
buff.Append(",");
}
}
sw.WriteLine(buff.ToString());
buff.Length = 0;
}
for (int r = 0; r < dt.Rows.Count; r++)
{
for (int c = 0; c < dt.Columns.Count; c++)
{
switch (dt.Columns[c].DataType.ToString().ToUpper())
{
case "SYSTEM.STRING":
case "SYSTEM.DATETIME":
buff.Append("\"" + dt.Rows[r][c].ToString() + "\"");
break;
default:
buff.Append(dt.Rows[r][c].ToString());
break;
}
if (c < (dt.Columns.Count - 1))
{
buff.Append(",");
}
}
sw.WriteLine(buff);
buff.Length = 0;
}
sw.Flush();
sw.Close();
sw = null;
return (0);
}
catch (System.Exception ex)
{
this.int_error_level = 1;
this.str_last_message = ex.Message.ToString();
return (-1);
}
}
Monday, January 29, 2007
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment