2009年7月22日 星期三

在 .Net 中透過 Excel 函數來計算並回傳值

*WinForm 或 Asp.Net 皆適用,本篇以 Asp.Net 為例

在 Excel 中有許多實用但計算功能複雜 function,所以很多人會使用 Excel 來做統計報表
但若要以程式實做這些功能耗時費力,所以若能直接利用 Excel 來幫忙計算可省去不少時間

在安裝 Excel 時,會同時將 Excel 註冊成 COM 元件,故在 .Net 可直接參考使用,如下圖##CONTINUE##

加入參考後當然就進行程式撰寫,程式流程如下

  1. 產生 Excel 物件及工作表
  2. 在 Cell 寫入數值及使用的 function(本範例使用 sum())
  3. 把值帶回 .Net 的變數

程式範例如下

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Excel;

public partial class _Default : System.Web.UI.Page
{
  protected void Page_Load(object sender, EventArgs e)
  {
    Application oExcel = new Application();
    Workbook oWorkBook = (Workbook)oExcel.Workbooks.Add(true);
    Worksheet oSheet = (Worksheet)oWorkBook.Sheets[1];
    Range cells = (Range)oSheet.Cells;

    cells[1, 1] = "1";
    cells[1, 2] = "2";
    Range oRet = (Range)cells[1, 3];

    oRet.Formula = "=sum(A1,B1)";
    Response.Write(oRet.Text.ToString());
  }
}

沒有留言:

張貼留言