Wednesday, September 23, 2009

Create Excel File

public static bool CreateExcelFile(DataTable dataTable, string fileName)
{
try
{
string str = "";
string str2 = "
";
string str3 = "";
string str4 = string.Empty;
StringBuilder builder = new StringBuilder();
foreach (DataColumn column in dataTable.Columns)
{
str3 = str3 + "" + column.ColumnName + "";
}
str3 = str3 + "";
foreach (DataRow row in dataTable.Rows)
{
builder.Append("");
for (int i = 0; i < dataTable.Columns.Count; i++)
{
str4 = " ";
if (!string.IsNullOrEmpty(row[i].ToString()))
{
str4 = row[i].ToString();
}
builder.Append("" + str4 + "");
}
builder.Append("");
}
string s = str + str3 + builder.ToString() + str2;
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + fileName);
HttpContext.Current.Response.Charset = "";
HttpContext.Current.Response.ContentType = "application/vnd.xls";
HttpContext.Current.Response.Write(s);
HttpContext.Current.Response.Flush();
return true;
}
catch
{
return false;
}
}

No comments: