第 2 步:创建托管代码 UDF

上次修改时间: 2010年1月21日

适用范围: SharePoint Server 2010

当向项目添加 Microsoft.Office.Excel.Server.Udf.dll 的引用之后,下一步便是创建某些自定义功能并用 Excel Services 用户定义函数 (UDF) 属性进行标记。

您必须用 Microsoft.Office.Excel.Server.Udf.UdfClass 属性来标记 UDF 类,并用 Microsoft.Office.Excel.Server.Udf.UdfMethod 属性来标记 UDF 方法。

任何未使用 UDF 程序集中的 Microsoft.Office.Excel.Server.Udf.UdfMethod 属性进行标记的方法都将被忽略,因为不会将其视为 UDF 方法。

Microsoft.Office.Excel.Server.Udf.UdfMethod 属性 (attribute) 具有一个 IsVolatile 属性 (property)。您可以使用 IsVolatile 属性 (property) 来指定某 UDF 方法是可变的还是稳定的。IsVolatile 属性 (property) 采用一个布尔值。默认值为 false,意味着该特定的 UDF 方法是稳定的。

创建 UDF

添加指令

  • 要使用的类型是在 Microsoft.Office.Excel.Server.Udf 命名空间中定义的。若在 Class1.cs 文件顶部添加 using(或 Imports)指令,则您无需完全限定命名空间中的类型,便可以使用 Microsoft.Office.Excel.Server.Udf 中的类型。

    若要添加此指令,请将以下代码添加到 Class1.cs 文件中代码的开头,using System.Text: 之后。

    using Microsoft.Office.Excel.Server.Udf; 
    
    Imports Microsoft.Office.Excel.Server.Udf
    

标记 UDF 类和方法

  1. 通过在 public class Class1 上方添加以下属性,可将 Class1 标记为 UDF 类:

    [UdfClass]
    
    <UdfClass>_
    
  2. 创建采用数字(double 类型)的函数,然后在函数中将该数字乘以 9。该函数是一个稳定的 UDF 方法。将下列代码添加到 Class1:

    [UdfMethod]
    public double MyDouble(double d)
    {
        return d * 9;
    }
    
    <UdfMethod> _
    Public Function MyDouble(ByVal d As Double) As Double
        Return d * 9
    End Function
    

    备注

    IsVolatile 属性的默认值为 false,这意味着该特定的 UDF 方法是稳定的。因此,将稳定的 UDF 方法标记为 [UdfMethod] 便已足够。无需将其标记为 [UdfMethod(IsVolatile = false)]。

  3. 创建另一个可使用 System.DateTime.Today 属性返回当前日期的函数。该函数是一个可变的 UDF 方法。将下列代码添加到 Class1:

    [UdfMethod(IsVolatile = true)]
    public DateTime ReturnDateTimeToday()
    {
        return (DateTime.Today);
    }      
    
    <UdfMethod(IsVolatile := True)> _
    Public Function ReturnDateTimeToday() As Date
        Return (Date.Today)
    End Function
    

生成项目:

  1. 在"生成"菜单中,单击"生成解决方案"。

  2. 您应在保存项目的目录下找到 SampleUdf.dll 程序集。

完整代码

以下代码示例是前面步骤中描述的 Class1.cs 示例文件中的完整代码。

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Office.Excel.Server.Udf;

namespace SampleUdf
{
    [UdfClass]
    public class Class1
    {
        [UdfMethod]
        public double MyDouble(double d)
        {
            return d * 9;
        }  

        [UdfMethod(IsVolatile = true)]
        public DateTime ReturnDateTimeToday()
        {
            return (DateTime.Today);
        }
    }
}
Imports System
Imports System.Collections.Generic
Imports System.Text
Imports Microsoft.Office.Excel.Server.Udf

Namespace SampleUdf
    <UdfClass> _
    Public Class Class1
        <UdfMethod> _
        Public Function MyDouble(ByVal d As Double) As Double
            Return d * 9
        End Function

        <UdfMethod(IsVolatile := True)> _
        Public Function ReturnDateTimeToday() As Date
            Return (Date.Today)
        End Function
    End Class
End Namespace

请参阅

任务

步骤 1:创建项目和添加 UDF 引用

步骤 3:部署和启用 UDF

步骤 4:从单元格测试和调用 UDF

如何:创建调用 Web 服务的 UDF

概念

演练:开发托管代码 UDF

了解 Excel Services UDF