程序员的部落

导航

DataSet导出为Excel

protected void Button1_Click(object sender, EventArgs e)
        {
            DataSet ds = new BLL.TrafficLine().GetAllList();
            DataTable dt = ds.Tables[0];

            string url = "D:\\"; //xls保存的路径
            string name = "cc";
            string type = "xls"; //type 就是要保存的文件后缀,可以为xls也可以为doc
            ///////////////////////
        
            StringWriter stringWriter = new StringWriter();
            HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);
            DataGrid excel = new DataGrid();
            System.Web.UI.WebControls.TableItemStyle AlternatingStyle = new TableItemStyle();
            System.Web.UI.WebControls.TableItemStyle headerStyle = new TableItemStyle();
            System.Web.UI.WebControls.TableItemStyle itemStyle = new TableItemStyle();
            AlternatingStyle.BackColor = System.Drawing.Color.LightGray;
            headerStyle.BackColor = System.Drawing.Color.LightGray;
            headerStyle.Font.Bold = true;
            headerStyle.HorizontalAlign = System.Web.UI.WebControls.HorizontalAlign.Center;
            itemStyle.HorizontalAlign = System.Web.UI.WebControls.HorizontalAlign.Center; ;

            excel.AlternatingItemStyle.MergeWith(AlternatingStyle);
            excel.HeaderStyle.MergeWith(headerStyle);
            excel.ItemStyle.MergeWith(itemStyle);
            excel.GridLines = GridLines.Both;
            excel.HeaderStyle.Font.Bold = true;
            excel.DataSource = dt.DefaultView;   //输出DataTable的内容
            excel.DataBind();
            excel.RenderControl(htmlWriter);

            string filestr = url + name + "." + type; //filePath是文件的路径
            int pos = filestr.LastIndexOf("\\");
            string file = filestr.Substring(0, pos);
            if (!Directory.Exists(file))
            {
                Directory.CreateDirectory(file);
            }
            System.IO.StreamWriter sw = new StreamWriter(filestr);
            sw.Write(stringWriter.ToString());
            sw.Close();

            Response.Write("ok");
        }

posted on 2009-04-02 10:15  程序员的部落  阅读(184)  评论(0编辑  收藏  举报