Wednesday, June 10, 2009

Download from Datatable to EXCEL/CSV

Code snippet to download from a datatable to Excel/CSV, for a given number of rows from a machine where Excel may not necessarily be installed.(I.E if you dont have office the file loads from any other editor that will load a CSV)


protected void ExportToExcel()
{
string query = @"AS
(
SELECT *, RANK() OVER(ORDER BY [column_name]) AS RankNumber FROM [table_name]
)
SELECT * FROM CTE WHERE RankNumber >= @StartRow AND RankNumber <= @EndRow";
SqlCommand cmd = new SqlCommand(query);
cmd.CommandType = CommandType.Text;
cmd.Connection = new SqlConnection("");
cmd.Parameters.AddWithValue("@StartRow", Page.Request.QueryString["StartRow"].ToString());
cmd.Parameters.AddWithValue("@EndRow", Page.Request.QueryString["EndRow"].ToString());
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
string name = "CSVExport";
HttpContext context = HttpContext.Current;
context.Response.Clear();
foreach (DataColumn column in dt.Columns)
{
context.Response.Write(column.ColumnName + ",");
}
context.Response.Write(Environment.NewLine);
foreach (DataRow row in dt.Rows)
{
for (int i = 0; i < dt.Columns.Count; i++)
{
context.Response.Write(row[i].ToString().Replace(",", string.Empty) + ",");
}
context.Response.Write(Environment.NewLine);
}
}

No comments:

Post a Comment