获取范围的绝对地址

Get absolute address of range

在旧学校 Excel Interop 中,我可以使用以下代码生成绝对地址并在公式中使用它:

range.Formula = $"=sum({myRange.Address[false, true]})";

此行的 EPPlus 等价物是什么,以获得绝对地址(根据需要具有绝对行 and/or 列)?

嗯,没有内置方法,但您可以执行以下操作:

string GetAddress(ExcelRange rgn, bool absoluteRow, bool absoluteColumn,bool includeSheetName=false)
{
    string address = rgn.Address;
    if (absoluteColumn)
    {
        address = Regex.Replace(address, @"\b([A-Z])", @"$$");
    }
    if (absoluteRow)
    {
        address = Regex.Replace(address, @"([0-9]+)", @"$$");
    }
    if (includeSheetName)
    {
        address = $"'{rgn.Worksheet.Name}'!{address}";
    }
    return address;
}

或者作为扩展方法,这样你就可以像互操作一样使用:

public static class EpplusExtensions
{
    public static string Address(this ExcelRange rgn, bool absoluteRow, bool absoluteColumn, bool includeSheetName=false)
    {
        string address = rgn.Address;
        if (absoluteColumn)
        {
            address = Regex.Replace(address, @"\b([A-Z])", @"$$");
        }
        if (absoluteRow)
        {
            address = Regex.Replace(address, @"([0-9]+)", @"$$");
        }
        if (includeSheetName)
        {
            address = $"'{rgn.Worksheet.Name}'!{address}";
        }
        return address;
    }
}

用法:

using (var ep = new ExcelPackage(new FileInfo(file)))
{
    var sh = ep.Workbook.Worksheets.First();
    ExcelRange myRange = sh.Cells[1, 1, 26, 36];
    var absoluteColumn = myRange.Address(false, true);
    var absoluteRow = myRange.Address(true, false);
    var absolute = myRange.Address(true, true);
    var relative = myRange.Address(false, false);
    var withSheetName = myRange.Address(true, true, true);
}

对于仅使用 EPPlus 方法的方法,有静态方法,如 ExcelCellBase.GetAddress(有几个重载)return 绝对地址:

public abstract class ExcelCellBase
{
    public static string GetAddress(
        int Row,
        int Column,
        bool Absolute
    );

    public static string GetAddress(
        int Row,
        bool AbsoluteRow,
        int Column,
        bool AbsoluteCol
    );

    public static string GetAddress(
          int FromRow,
          int FromColumn,
          int ToRow,
          int ToColumn,
          bool FixedFromRow,
          bool FixedFromColumn,
          bool FixedToRow,
          bool FixedToColumn
    );

    /* ... and others, see comments */
}

扩展方法可以像这个一样简单:

public static class EpPlusExtensions
{
    public static string GetAddress(
        this ExcelRangeBase range,
        bool absoluteRow = false,
        bool absoluteColumn = false)
    {
        return ExcelCellBase.GetAddress(
            range.Start.Row,
            range.Start.Column,
            range.End.Row,
            range.End.Column,
            absoluteRow,
            absoluteColumn,
            absoluteRow,
            absoluteColumn);
    }
}