protected void Button1_Click(object sender, EventArgs e)
        {
            string fileName = "WLSearch_Favorites.xls";
            string sendMethdo = this.DropDownList1.Text;
            object[] obj = { sendMethdo };
            DataTable dt = CM.DataAccess.dataDrive.WelanMain.connProcedureExec("CustomerAddress", obj).Tables[0];
            ExportEasy(dt, fileName);


            fileName = HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8);//解决导出EXCEL时乱码的问题

            Response.Clear();
            Response.Buffer = true;
            Response.Charset = "GB2312"; //设置了类型为中文防止乱码的出现
            Response.AppendHeader("Content-Disposition", "attachment;filename=" + fileName); //定义输出文件和文件名
            Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");//设置输出流为简体中文
            Response.ContentType = "application/ms-excel";//设置输出文件类型为excel文件。
            this.EnableViewState = false;
            System.Globalization.CultureInfo myCItrad = new System.Globalization.CultureInfo("ZH-CN", true);
            System.IO.StringWriter oStringWriter = new System.IO.StringWriter(myCItrad);
            System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);

            GridView gv = new GridView();

            gv.DataSource = dt;
            gv.DataBind();
            gv.RenderControl(oHtmlTextWriter);


            Response.Write(oStringWriter.ToString());
            Response.End();
            Response.Write("<script>window.close();</script>");
        }
        public static void ExportEasy(DataTable dtSource, string strFileName)
        {
            HSSFWorkbook workbook = new HSSFWorkbook();
            HSSFSheet sheet = workbook.CreateSheet();

            //填充表头
            HSSFRow dataRow = sheet.CreateRow(0);
            foreach (DataColumn column in dtSource.Columns)
            {
                dataRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
            }
            //填充内容
            for (int i = 0; i < dtSource.Rows.Count; i++)
            {
                dataRow = sheet.CreateRow(i + 1);
                for (int j = 0; j < dtSource.Columns.Count; j++)
                {
                    dataRow.CreateCell(j).SetCellValue(dtSource.Rows[i][j].ToString());
                }
            }
            //保存
            using (MemoryStream ms = new MemoryStream())
            {
                using (FileStream fs = new FileStream(strFileName, FileMode.Create, FileAccess.Write))
                {
                    workbook.Write(fs);
                }
            }
        }

=====================================================================

posted on 2011-02-18 15:47  高兴happy  阅读(306)  评论(0编辑  收藏  举报