通过 Excel 的自动化外接程序,可以将 COM 库的公共函数作为单元格公式进行调用。下面的示例演示如何创建 C# 外接程序,用于在 Excel 工作表的单元格中计算所得税税率。ComRegisterFunctionAttribute 自动注册该外接程序,无需任何其他工具即可将托管代码注册为 COM 程序集。有关其他信息,请参见互操作性概述(C# 编程指南)

Note注意

显示的对话框和菜单命令可能会与“帮助”中描述的不同,具体取决于您现用的设置或版本。若要更改设置,请在“工具”菜单上选择“导入和导出设置”。有关更多信息,请参见 Visual Studio 设置

计算所得税

给定个人年收入,即可使用典型税表计算所得税。例如,下面为一个假设的个人所得税表。

示例税表

  1. 如果收入在零美元和 $7,000 之间,则税款为金额的 10%。

  2. 如果收入在 $7,000 和 $28,400 之间,则税款是超过 $7,000 的部分乘以 15% 再加上 $700.00。

  3. 如果收入在 $28,400 和 $68,800 之间,则税款是超过 $28,400 的部分乘以 25% 再加上 3,910.00。

  4. 如果收入在 $68,800 和 $143,500 之间,则税款是超过 $68,800 的部分乘以 28% 再加上 $14,010.00。

  5. 如果收入在 $143,500 和 $311,950 之间,则税款是超过 $143,500 的部分乘以 33% 再加上 $34,926.00。

  6. 如果收入高于 $311,950,则税款是超过 $311,950 的部分乘以 35% 再加上 $90,514.50。

使用 Visual Studio 和托管代码创建 Excel 的自动化外接程序

  1. 创建名为 ExcelAddIn 的新 Visual C#“类库”项目。

  2. 在“项目属性”窗口中,在“配置属性”->“生成”下,从标记为“为 COM Interop 注册”的下拉框中,选择 True。Visual Studio 项目的这一生成属性设置将自动为 COM 互操作性注册程序集。

  3. 将下面的代码粘贴到类文件中。

    C# CopyCode image复制代码
    using System.Runtime.InteropServices;
    
    namespace TaxTables
    {
        [ClassInterface(ClassInterfaceType.AutoDual)]
        public class TaxTables
        {
            public static double Tax(double income)
            {
                if (income >      0 && income <=   7000) {return            (.10 * income);}
                if (income >   7000 && income <=  28400) {return   700.00 + (.15 * (income - 7000));}
                if (income >  28400 && income <=  68800) {return  3910.00 + (.25 * (income - 28400));}
                if (income >  68800 && income <= 143500) {return 14010.00 + (.28 * (income - 68800));}
                if (income > 143500 && income <= 311950) {return 34926.00 + (.33 * (income - 143500));}
                if (income > 311950)                     {return 90514.50 + (.35 * (income - 311950));}
                return 0;
            }
    
            [ComRegisterFunctionAttribute]
            public static void RegisterFunction(System.Type t)
            {
                Microsoft.Win32.Registry.ClassesRoot.CreateSubKey
                    ("CLSID\\{" + t.GUID.ToString().ToUpper() + "}\\Programmable");
            }
    
            [ComUnregisterFunctionAttribute]
            public static void UnregisterFunction(System.Type t)
            {
                Microsoft.Win32.Registry.ClassesRoot.DeleteSubKey
                    ("CLSID\\{" + t.GUID.ToString().ToUpper() + "}\\Programmable");
            }
        }
    }
    

运行代码

运行 Excel 外接程序

  • 生成 ExcelAddIn 项目,按 F5 进行编译。

  • 在 Excel 中打开一个新工作簿。

  • 从“工具”菜单上单击“外接程序”,然后单击“自动化”。

  • 在“自动化服务器”对话框中,选择外接程序列表中的“ExcelAddIn”,然后单击“确定”。

  • 在一个工作簿单元格中,键入 =Tax(23500)。该单元格将显示 3175。

  • 若要在将 ExcelAddIn.dll 移动到其他目录后进行注册,请运行带 /codebaseregasm。可能会收到警告,指示该程序集未签名。

  • 注意,显示的对话框和菜单命令可能会与“帮助”中的描述不同,具体取决于您现用的设置或版本。若要更改设置,请在“工具”菜单上选择“导入和导出设置”。有关更多信息,请参见 Visual Studio 设置。

安全

若要使用 COM 互操作性,您必须具有管理员或超级用户的安全权限。有关更多信息,请参见“.NET Framework Security”(.NET Framework 安全性)

请参见