Adding hyperlinks in Excel[2007] in C# - Within Excel it self

前端 未结 4 2113
醉梦人生
醉梦人生 2021-02-08 11:00

Can anybody tell me how we can add a hyperlink in Excel (2007 or later) from a cell in one sheet to a cell in another sheet using Office Interop in .NET (c#)

For example

4条回答
  •  迷失自我
    2021-02-08 11:35

    What you want to use here is the Hyperlinks.Add method.

    You can call it with code that looks something like this:

    Excel.Worksheet worksheet = (Excel.Worksheet)workbook.Worksheets[1];
    Excel.Range rangeToHoldHyperlink = worksheet.get_Range("A1", Type.Missing);
    string hyperlinkTargetAddress = "Sheet2!A1";
    
    worksheet.Hyperlinks.Add(
        rangeToHoldHyperlink,
        string.Empty,
        hyperlinkTargetAddress,
        "Screen Tip Text",
        "Hyperlink Title");
    

    Here is a full automation example that you can test:

    void AutomateExcel()
    {
        Excel.Application excelApp = new Excel.Application();
        excelApp.Visible = true;
    
        Excel.Workbook workbook = excelApp.Workbooks.Add(Type.Missing);
        workbook.Worksheets.Add(Type.Missing, Type.Missing, Type.Missing, Type.Missing);
        workbook.Worksheets.Add(Type.Missing, Type.Missing, Type.Missing, Type.Missing);
    
        Excel.Worksheet worksheet = (Excel.Worksheet)workbook.Worksheets[1];
        Excel.Range rangeToHoldHyperlink = worksheet.get_Range("A1", Type.Missing);
        string hyperlinkTargetAddress = "Sheet2!A1";
    
        worksheet.Hyperlinks.Add(
            rangeToHoldHyperlink,
            string.Empty,
            hyperlinkTargetAddress,
            "Screen Tip Text",
            "Hyperlink Title");
    
        MessageBox.Show("Ready to clean up?");
    
       // Cleanup:
        GC.Collect();
        GC.WaitForPendingFinalizers();
        GC.Collect();
        GC.WaitForPendingFinalizers();
    
        Marshal.FinalReleaseComObject(range);
    
        Marshal.FinalReleaseComObject(worksheet);
    
        workbook.Close(false, Type.Missing, Type.Missing);
        Marshal.FinalReleaseComObject(workbook);
    
        excelApp.Quit();
        Marshal.FinalReleaseComObject(excelApp);
    }
    

    Hope this helps!

    Mike

提交回复
热议问题