2021年4月29日 星期四

[C# ASP.NET]利用ClosedXML在網頁上簡單輸出EXCEL檔

  最近嘗試用RDLC之外的方法來匯出Excel,想說是否可以直接輸出EXCEL檔,而不用另外再繪製報表檔。之後網路上找到方便的Open Source程式庫 ClosedXML,此程式庫可簡單的去處理EXCEL物件進而直接輸出到網頁,語法使用上也非常簡單,所以在此紀錄一下。

下載方式:
  可以直接用NuGet下載至專案,也可到Github上下載。
但程式庫和DocumentFormat.OpenXml.dll有相依,NuGet會幫你引用;自行下載的話需要記得引用。

程式寫法:

    //資料連線字串
    string strConn = "Integrated Security=false;User ID=xxxx;pwd=****;Initial Catalog=DataName;Data Source=SQLEXPRESS";
    using (SqlConnection Conn = new SqlConnection())
    {
        //開啟連線
        Conn.ConnectionString = strConn;
        Conn.Open();
        //SQL查詢字串
        string strSQL = "Select * From TableA";
        SqlCommand cmd = new SqlCommand(strSQL, Conn);

        //讀取SQL資料
        SqlDataReader SqlDR = cmd.ExecuteReader();
        DataTable dtSource = new DataTable();
        dtSource.Load(SqlDR);

        //釋放
        SqlDR.Close();
        SqlDR.Dispose();
        SqlDR = null;
        //關閉連線
        Conn.Close();

        //EXCEL物件
        ClosedXML.Excel.XLWorkbook xlwb = new ClosedXML.Excel.XLWorkbook();
        //塞入DataTable資料
        xlwb.AddWorksheet(dtSource, "匯出資料");

        //清空輸出
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.Buffer = true;
        //設定MIME類型
        HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=Text.xlsx");

        //記憶體資料流
        using (MemoryStream ms = new MemoryStream())
        {
            //EXCEL物件寫入到記憶體資料流
            xlwb.SaveAs(ms);
            //轉寫到輸出資料流
            ms.WriteTo(HttpContext.Current.Response.OutputStream);
            ms.Close();

            //輸出
            HttpContext.Current.Response.Flush();
            HttpContext.Current.Response.End();
        }
    }
    

如此就可讀取SQL資料庫的內容直接輸出到Client端成EXCEL檔下載。
 


沒有留言:

張貼留言