如何从数据库中检索数据到word文档。净

时间:2011-03-29 05:30:58

标签: .net sql-server database ms-word

我必须将数据表格数据库检索到word文档和excel表格,但我能够将其用于excel表格&不适用于ms word或pdf。谁能建议我怎么做? 这是我在.net中的代码:

    protected void btnExportToExcel_Click(object sender, EventArgs e)
    {
        Response.Clear();
        Response.AddHeader("content-disposition", "attachment;filename=DocumentReport.xls");
        Response.Charset = "";
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.ContentType = "application/vnd.ms-excel";
        System.IO.StringWriter stringWrite = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
        GridView1.RenderControl(htmlWrite);
        Response.Write(stringWrite.ToString());
        Response.End();
    }
    protected void btnExportToWord_Click(object sender, EventArgs e)
    {
        Response.Clear();
        Response.AddHeader("content-disposition", "attachment;filename=DocumentReport.docx");
        Response.Charset = "";
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.ContentType = "application/vnd.ms-word";
        System.IO.StringWriter stringWrite = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
        GridView1.RenderControl(htmlWrite);
        Response.Write(stringWrite.ToString());
        Response.End();
    }

2 个答案:

答案 0 :(得分:0)

好。你的代码似乎在我的最后工作。您在出口期间是否收到任何异常?我也在不久前收到同样的事情。

我刚刚在aspx页面的Page指令中创建了 EnableEventValidation =“false”并且它工作正常。你也可以试试。 它应该工作。

答案 1 :(得分:0)

尝试将内容类型更改为 Response.AppendHeader(“Content-Type”,“application / msword”); 还要确保你是否使用“css”样式在你要渲染的字符串中包含样式。