导出excel/xml

1.GridView导出Excel表

protected void Page_Load(object sender, EventArgs e)   { if (!IsPostBack)  BindData(); }
private void BindData() {...}
protected void Button1_Click(object sender, EventArgs e)
    {
        GridView1.AllowPaging = false;  //导出Gv的全部页数据,不加则导出一页
        BindData();
        Response.Clear();
        Response.Buffer = true;
        Response.Charset = "GB2312";
        Response.AppendHeader("Content-Disposition", "attachment;filename=FileName.xls");
        Response.ContentEncoding = System.Text.Encoding.UTF7;   // GetEncoding("GB2312")会乱码
        Response.ContentType = "application/ms-excel";    //输出类型为excel ,要输出word时为ms-word
        System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
        this.GridView1.RenderControl(oHtmlTextWriter);
        Response.Output.Write(oStringWriter.ToString());
        Response.Flush();
        Response.End();
        GridView1.AllowPaging = true;
        BindData();
    }

public override void VerifyRenderingInServerForm( Control control )  { }  //不加此函数会出现导出错误

 

2.定时自动导出XML(即无保存提示)

  //content:<news><newsid>..</newsid><newstitle>...</newstitle>..</news>
    //fileName:news.xml
    //filePath:@"D:\XML\"
    //web.config的路径配置可以是:D:\XML\,D:\\XML\\,D:/XML/,但D:\,D:\\不行,D:\\XML不是期望值
    private void OutXmlFile(string content, string fileName, string filePath)
    {
        XmlDocument doc = new XmlDocument();
        doc.LoadXml(content);

        XmlDeclaration xmldecl = doc.CreateXmlDeclaration("1.0", "utf-8", null);
        XmlElement root = doc.DocumentElement;
        doc.InsertBefore(xmldecl, root);

        if (!Directory.Exists(Path.GetDirectoryName(filePath))) Directory.CreateDirectory(Path.GetDirectoryName(filePath));
        doc.Save(filePath + fileName);
    }

 

 

posted @ 2009-07-27 19:08  DaCHun  阅读(429)  评论(0编辑  收藏  举报