ASP.NET 將DataTable匯入到Excel

來源:互聯網
上載者:User

今天在弄頁面上的列印功能,就是把Gridview裡的資料列印出來。首先就是將Gridv裡的資料匯入到Excel,再列印,很簡單。然而,到網上找了很多資料,就是不行。

有好幾個錯誤,記得最清楚的是Clsid{……}錯誤。按照網友說的,做了也不行。

竟然把代碼拷到同事的機器上,就行了。啥原因?同事的機上安裝的是101M的office 2003。我的機子上的Office是綠化版。我也安了那個101M的office 2003,結果就行了。

操作過程:
添加引用.NET下Microsoft.Office.Interop.Excel      11.0.0.0     v1.1.4322
到項目中,Bin下會有Microsoft.Office.Interop.Excel.dll

列印類

Code
 /// <summary>
    /// 匯出到Excel
    /// </summary>
    /// <param name="dt">DataTable</param>
    /// <param name="filepath">要匯出的路徑,可以為空白</param>
    /// <returns></returns>
    public static string ExportExcel(System.Data.DataTable dt, string filepath) //把DataTable裡的資料匯入到Excel
    {
        if (filepath == null || filepath == "")
        {
            filepath = HttpContext.Current.Server.MapPath("~/");
            filepath = filepath + "test.xls";
        }
        Application xlApp = new Application();
        if (xlApp == null)
        {
            return "你的機子上沒有安裝Excel!";
        }
        Workbooks workbooks = xlApp.Workbooks;
        
        Workbook workbook = workbooks.Add(XlWBATemplate.xlWBATWorksheet);
        Worksheet worksheet = (Worksheet)workbook.Worksheets[1];//取得sheet1 
     
        //寫入欄位 
        for (int i = 0; i < dt.Columns.Count; i++)
        {
            worksheet.Cells[1, i + 1] = dt.Columns[i].ColumnName;
        }
        //寫入數值 
        for (int r = 0; r < dt.Rows.Count; r++)
        {
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                worksheet.Cells[r + 2, i + 1] = dt.Rows[r][i];
            }
        }
        worksheet.Columns.EntireColumn.AutoFit();//列寬自適應。

        workbook.Saved = true;
        workbook.SaveCopyAs(filepath);

        xlApp.Quit();
        GC.Collect();//強行銷毀 

        HttpContext.Current.Response.Buffer = true;
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.ContentType = "application/ms-excel";
        HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(filepath));
        HttpContext.Current.Response.WriteFile(filepath);
        HttpContext.Current.Response.Flush();
        HttpContext.Current.Response.End();

        return "";
    }

後面那段Response 是讓excel以下載的形式開啟。

 

 

PS:html方式匯出Excel

HTML方式匯出Excel

 Response.Clear();
Response.Buffer = true;

Response.Charset = "utf-8";

//下面這行很重要, attachment 參數表示作為附件下載,您可以改成 online線上開啟

//filename=FileFlow.xls 指定輸出檔案的名稱,注意其副檔名和指定檔案類型相符,可以為:.doc    .xls    .txt   .htm  

Response.AppendHeader("Content-Disposition", "attachment;filename=" + Utils.UrlEncode(filename) + ".xls");

Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");

//Response.ContentType指定檔案類型 可以為application/ms-excel    application/ms-word    application/ms-txt    application/ms-html    或其他瀏覽器可直接支援文檔 

Response.ContentType = "application/ms-excel";

this.EnableViewState = false;


System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);

this.RenderControl(oHtmlTextWriter);
//this 表示輸出本頁,你也可以綁定datagrid,或其他支援obj.RenderControl()屬性的控制項  

Response.Write(oStringWriter.ToString());

Response.End();

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.