SqlConnection conn = new SqlConnection();
SqlCommand com = new SqlCommand();
conn.ConnectionString = "TYPE CONNECTION STRING HERE";
string query_str = "WRITE QUERY HERE";
com.CommandText = query_str;
com.CommandType = CommandType.Text;
com.Connection = conn;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = com;
DataSet ds = new DataSet();
da.Fill(ds);
DataTable dt = ds.Tables[0];
HttpContext context = HttpContext.Current;
context.Response.Clear();
context.Response.ContentType = "text/csv";
context.Response.AddHeader("Content-Disposition","attachment; Filename = FILE.csv");
for (int i = 0; i < dt.Columns.Count - 1 ; i++)
{
if (i > 0) context.Response.Write(",");
context.Response.Write(dt.Columns[i].ColumnName);
}
context.Response.Write(Environment.NewLine);
foreach (DataRow dr in dt.Rows)
{
for (int i = 0; i < dt.Columns.Count - 1; i++)
{
if (i > 0) context.Response.Write(",");
context.Response.Write(dr.ItemArray[i].ToString());
}
context.Response.Write(Environment.NewLine);
}
context.Response.End();
SqlCommand com = new SqlCommand();
conn.ConnectionString = "TYPE CONNECTION STRING HERE";
string query_str = "WRITE QUERY HERE";
com.CommandText = query_str;
com.CommandType = CommandType.Text;
com.Connection = conn;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = com;
DataSet ds = new DataSet();
da.Fill(ds);
DataTable dt = ds.Tables[0];
HttpContext context = HttpContext.Current;
context.Response.Clear();
context.Response.ContentType = "text/csv";
context.Response.AddHeader("Content-Disposition","attachment; Filename = FILE.csv");
for (int i = 0; i < dt.Columns.Count - 1 ; i++)
{
if (i > 0) context.Response.Write(",");
context.Response.Write(dt.Columns[i].ColumnName);
}
context.Response.Write(Environment.NewLine);
foreach (DataRow dr in dt.Rows)
{
for (int i = 0; i < dt.Columns.Count - 1; i++)
{
if (i > 0) context.Response.Write(",");
context.Response.Write(dr.ItemArray[i].ToString());
}
context.Response.Write(Environment.NewLine);
}
context.Response.End();
No comments:
Post a Comment