将DATASET中的内容导出到EXCEL

时间:2021-08-29 09:32:07

1.点击按钮导出

<asp:Button ID="btnExport" runat="server" class="bb_b"   Text="导 出" onclick="btnExport_Click" Height="26px" style="width: 73px"/>

2.触发点击事件

 protected void btnExport_Click(object sender, EventArgs e)
        {
             string js = "alert('没有可以导出的项目!')";
                ConvertToExcel1(0);
 
        }

 

 

private void ConvertToExcel1(int k)
        {
            DataTable dtMain = new DataTable();
            DataTable dtDetail = new DataTable();
            DataSet dsExport = GetDataBindPrint(dtMain, dtDetail);
            string FileName = "数据统计" + DateTime.Now.ToString("yyyyMMddHHmmss");//excel文件名称

            HttpResponse resp;
            resp = Page.Response;
            resp.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
            resp.ContentType = "application/ms-excel";
            resp.AddHeader("Content-Disposition", "attachment; filename=" + System.Web.HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8) + ".xls");
            this.EnableViewState = false;

            string colHeaders = "", Is_item = "";
            int i = 0;

            //定义表对象与行对象,同时使用DataSet对其值进行初始化
            DataTable dt = dsExport.Tables[k];
            DataRow[] myRow = dt.Select("");

            //取得数据表各列标题,标题之间以\t分割,最后一个列标题后加回车符
            for (i = 0; i < dt.Columns.Count; i++)
            {
                colHeaders += dt.Columns[i].Caption.ToString() + "\t";
            }
            colHeaders += "\n";

            resp.Write(colHeaders);
            //逐行处理数据
            foreach (DataRow row in myRow)
            {
                //在当前行中,逐列取得数据,数据之间以\t分割,结束时加回车符\n
                for (i = 0; i < dt.Columns.Count; i++)
                {
                    Is_item += row[i].ToString() + "\t";
                }
                Is_item += "\n";
                resp.Write(Is_item);
                Is_item = "";
            }

            //写缓冲区中的数据到HTTP头文件中
            resp.End();

        }