匯出Excel或word文件

笨笨鼠→_→發表於2012-07-06

#region 匯出檔案方法
    /// <summary>
    /// 匯出檔案方法
    /// </summary>
    /// <param name="exportFileName">匯出檔案的名字(包括字尾名,word為: .doc,excel為: .xls)</param>
    /// <param name="mime">MIME碼(Word為:"application/ms-word",Excel為:"application/ms-excel")</param>
    /// <param name="control">匯出的控制元件</param>

    private void ExportFile(string exportFileName, string mime, Control control)
    {
        Response.Clear();
        Response.Buffer = true;
        Response.Charset = "GB2312";
        Response.AppendHeader("Content-Disposition", "attachment;filename=" + exportFileName);
        //設定輸出流為簡體中文 
        Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");   
        //設定輸出檔案型別。
        Response.ContentType = mime;
        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);
        control.RenderControl(oHtmlTextWriter);
        Response.Write(oStringWriter.ToString());
        Response.End();
    }

    // 使用匯出方法,必須要重寫的方法,否則會報錯 :
    //型別“xxx”的控制元件“xxx”必須放在具有 runat=server 的窗體標記內
    public override void VerifyRenderingInServerForm(Control control)
    {
        // 空
    }
    #endregion


相關文章