优化添加超链接语法

时间:2017-02-15 14:31:41

标签: c# excel performance c#-4.0 hyperlink

我有一个工作表,我在其中添加了500个超链接,此过程大约需要90秒才能完成。我知道部分原因是由于被迫使用Microsoft Interop Excel,部分原因是被迫使用for loop,但必须有一种更快/更有效的方法来实现这一目标。这是我目前的语法

public static void AddThatHyper()
{
    long lr, i;
    string cellVal;
    WS = xlApp.ActiveWorkbook.ActiveSheet;
    lr = WS.Cells[WS.Rows.Count, 2].End(Excel.XlDirection.xlUp).Row;
    for (i = 2; i <= lr; i++)
    {
        Object Anchor = WS.Cells[i, 9];
        Object TextToDisplay = Convert.ToString(WS.Cells[i, 9]);
        cellVal = WS.Cells[i, 1].Value;
        cellVal = cellVal.Substring(0, Math.Min(28, cellVal.Length));
        rangeToHoldHyperlink = WS.Range["I" + i];

        if (cellVal.Contains("&") ||
            cellVal.Contains(",") ||
            cellVal.Contains("-") ||
            cellVal.Contains(".")
           )
        {
            xlApp.ActiveSheet.Hyperlinks.Add(Anchor, "", "'" + "CR " + cellVal + "'!A1", "", TextToDisplay);
        }
        if (cellVal.Contains("'"))
        {
            cellVal = cellVal.Replace("'", "''");
            xlApp.ActiveSheet.Hyperlinks.Add(Anchor, "", "'" + "CR " + cellVal + "'!A1", "", TextToDisplay);
        }
        else
        {
            xlApp.ActiveSheet.Hyperlinks.Add(Anchor, "", "'" + "FR " + cellVal + "'!A1", "", TextToDisplay);
        }
    }
}

可以在此处做些什么来优化此语法并在更快的时间范围内完成?

1 个答案:

答案 0 :(得分:0)

注意,此代码未经过测试。这是基于我之前制作的程序的一个例子。您可能需要进行一些手动调试,以查看是否正在提取/转换值。

public static void AddThatHyper()
{
    long lr, i;
    string cellVal;
    WS = xlApp.ActiveWorkbook.ActiveSheet;
    lr = WS.Cells[WS.Rows.Count, 2].End(Excel.XlDirection.xlUp).Row;
    string prefix = "";      

    string topCell = "I" + 2;
    string bottomCell = "I" + lr;

    //get_Range returns object array
    Range range = ws.get_Range(topCell, bottomCell);

    object[,] rangeValues = new object[lr - 2, 1];
    string[,] rangeStringValues = new string[lr - 2, 1];
    rangeValues = range.Cells.Formula;

    //turn object array into string array
    //should contain strings like "=hyperlink(url, text)"
    for (int i = 0; i < rangeValues.GetLength(0); i++)
    {
        rangeStringValues[i, 0] = rangeValues[i, 0]?.ToString() ?? "";
    }

    //edit hyperlinks
    for (int i = 0; i < rangeStringValues.GetLength(0); i++)
    {
        prefix = "FR"
        string hyperlink = rangeStringValues[i, 0];
        MatchCollection fields =  Regex.Matches(hyperlink, @"("[A-Za-z0-9\.]*")");
        string url = fields[0]?.ToString() ?? "";
        string text = fields[1]?.ToString() ?? "";

        if (Regex.IsMatch(url, @"[&,\-\.]"))
            prefix = "CR";
        else if (url.Contains("'"))
        {
            prefix = "CR"
            url.Replace("'", "''");
        }
        string formattedUrl = "'" + prefix + url + "'!A1";
        rangeStringValues[i, 0]= $"=HYPERLINK(""{formattedUrl }"", ""{text}"")";

    }
    range.set_Value(value: values);
    range.Formula = range.Value;
}