Send query results to Excel from ASP.NET website

后端 未结 7 1080
失恋的感觉
失恋的感觉 2020-12-17 03:03

We let users create ad-hoc queries in our website. We would like to have the user select their criteria, then click submit and have the results streamed automatically to Ex

7条回答
  •  北海茫月
    2020-12-17 03:29

    I got a utils function that does this already. Once you put it into a datatable, you can export it with the Response using

            public static void DataTabletoXLS(DataTable DT, string fileName)
        {
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.Charset = "utf-16";
            HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("windows-1250");
            HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}.xls", fileName));
            HttpContext.Current.Response.ContentType = "application/ms-excel";
    
            string tab = "";
            foreach (DataColumn dc in DT.Columns)
            {
                HttpContext.Current.Response.Write(tab + dc.ColumnName.Replace("\n", "").Replace("\t", ""));
                tab = "\t";
            }
            HttpContext.Current.Response.Write("\n");
    
            int i;
            foreach (DataRow dr in DT.Rows)
            {
                tab = "";
                for (i = 0; i < DT.Columns.Count; i++)
                {
                    HttpContext.Current.Response.Write(tab + dr[i].ToString().Replace("\n", "").Replace("\t", ""));
                    tab = "\t";
                }
                HttpContext.Current.Response.Write("\n");
            }
            HttpContext.Current.Response.End();
                   }
    

提交回复
热议问题