顯示具有 C# 標籤的文章。 顯示所有文章
顯示具有 C# 標籤的文章。 顯示所有文章

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());
  }
}

2009年6月28日 星期日

在 WinForm 鎖住鍵盤,不能輸入任何訊息

在Form中鎖住鍵盤,僅能透過滑鼠或其他輸入設備來與電腦進行互動

1. 新增一 Windows 應用程式專案

2. 修改 Program.cs
把 main 改為
static void Main()
{
RButtonMessageFilter filter = new RButtonMessageFilter();
Application.AddMessageFilter(filter);

Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());

Application.RemoveMessageFilter(filter);
}
3. 新增一 Class##CONTINUE##
using System.Windows.Forms;
public class RButtonMessageFilter : IMessageFilter
{
public bool PreFilterMessage(ref Message m)
{
const int WM_KEYDOWN = 0x100;

switch (m.Msg)
{
case WM_KEYDOWN:
{
return true;
}
default:
{
return false;
}
}
}
}