Share via


How to add a hyperlink to direct to another worksheet in the same workbook in Excel, by C#

Question

Wednesday, February 28, 2018 4:54 PM

The program I'm working on will output a large number of worksheets into an Excel file, so I will add an index worksheet with links to each of them. How can I add a hyperlink to turn to different worksheet in a certain cell?

I found a lot of examples online, however, all rely on commercial .dll or objects.

Is there any method for this in the common Microsoft.Office.Interop.Excel object?

Thanks!

All replies (2)

Thursday, March 1, 2018 2:01 AM

Hello Victor Soong,

Please check if below code could work for you.

using Excel = Microsoft.Office.Interop.Excel;




 //application is the application instance of the excel
            Excel.Workbook workbook = application.ActiveWorkbook;
            Excel.Worksheet IndexSheet = workbook.Sheets[1];
            Excel.Worksheet newAddSheet;
            for (int i = 1; i < 5; i++) {
                newAddSheet = workbook.Worksheets.Add();
                IndexSheet.Hyperlinks.Add(IndexSheet.Cells[i, 1], "", newAddSheet.Range["A1"].Address[External:true],"",newAddSheet.Name);
            }

Best Regards.

Terry

MSDN Community Support
Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact [email protected].


Thursday, March 1, 2018 2:52 AM

Hi Victor,

The following solution is based on a free dll named free spire.xls which you can get from nuget, I hope it's helpful.

//Load workbook
Workbook workbook = new Workbook();
workbook.LoadFromFile("Input.xlsx");

//Get the first worksheet
Worksheet sheet = workbook.Worksheets[0];

//Link to cell "B5" in Sheet2
CellRange range = sheet.Range["B5"];
HyperLink link = sheet.HyperLinks.Add(range);
link.Type = HyperLinkType.Workbook;
link.TextToDisplay = "Go to sheet 2";
link.Address = "Sheet2!B5";

//Save the workbook
workbook.SaveToFile("Output.xlsx", ExcelVersion.Version2013);