Adding Hyperlinks in an Excel document in C# and .NET

Excel is one of the most common tools for working with data. When it comes to creating dynamic and interactive reports, the ability to add hyperlinks to Excel documents becomes especially relevant. In this article, we will look at how to implement this feature using the SautinSoft.Excel library using C# and .NET.

Adding hyperlinks to Excel has many advantages:

  • Simplify navigation. Hyperlinks allow users to quickly navigate to related data, documentation, or web resources without having to manually search for information.
  • Interactivity. Using hyperlinks makes the document more interactive, which can improve the perception of information and make interaction with the report more convenient.
  • Links to sources. In scientific or research reports, hyperlinks can be used to point to data sources, which increases the credibility of the information provided.
  • Simplify collaboration. When a document contains links to shared resources or folders, it can make it easier for project participants to work together.

Step-by-step guide:

  1. Add SautinSoft.Excel from Nuget.
  2. Create a new Excel document and add an empty worksheet.
  3. Add hyperlinks into document.
  4. Save the Excel document.

Полный код

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using SautinSoft.Excel;
using SkiaSharp;

namespace Example
{
    class Program
    {
        static void Main(string[] args)
        {
            // Get your free key here:   
            // https://sautinsoft.com/start-for-free/

            AllTypesOfHyperlinks();
        }

        /// <summary>
        /// Inserting 2 types of hyperlinks into the cells.
        /// </summary>
        /// <remarks>
        /// Details: https://www.sautinsoft.com/products/excel/help/net/developer-guide/using-hyperlinks-xlsx-net-csharp-vb.php
        /// </remarks>
        static void AllTypesOfHyperlinks()
        {
            string outFile = @"..\..\..\Result.xlsx";
            // The file format is detected automatically from the file extension: ".xlsx".
            ExcelDocument excel = new ExcelDocument();

            // Add an empty worksheet to the file.
            excel.Worksheets.Add("Page 1");
            excel.Worksheets.Add("Page 2");
            var worksheet = excel.Worksheets["Page 1"];


            // Add hyperlinks into document.
            worksheet.Cells["A1"].Value = "External link";
            worksheet.Cells["A1"].Hyperlink = new ExcelHyperlink { Location = "https://sautinsoft.com", ToolTip = "SautinSoft" };

            worksheet.Cells["A2"].Value = "Internal link";
            worksheet.Cells["A2"].Hyperlink = new ExcelHyperlink { Location = "\'Page 2\'!A1", ToolTip = "A1 cell on another page" };
            

            // Expand the column to make it look attractive
            worksheet.Columns["A"].AutoFit();

            // Saving the excel document.
            excel.Save(outFile);

            // Important for Linux: Install MS Fonts
            // sudo apt install ttf-mscorefonts-installer -y

            // Open the result for demonstration purposes.
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(outFile) { UseShellExecute = true });
        }
    }
}

Download

Option Infer On

Imports System
Imports System.Collections.Generic
Imports System.IO
Imports System.Text
Imports SautinSoft.Excel
Imports SkiaSharp

Namespace Example
	Friend Class Program
		Shared Sub Main(ByVal args() As String)
			' Get your free key here:   
			' https://sautinsoft.com/start-for-free/

			AllTypesOfHyperlinks()
		End Sub

		''' <summary>
		''' Inserting 2 types of hyperlinks into the cells.
		''' </summary>
		''' <remarks>
		''' Details: https://www.sautinsoft.com/products/excel/help/net/developer-guide/using-hyperlinks-xlsx-net-csharp-vb.php
		''' </remarks>
		Private Shared Sub AllTypesOfHyperlinks()
			Dim outFile As String = "..\..\..\Result.xlsx"
			' The file format is detected automatically from the file extension: ".xlsx".
			Dim excel As New ExcelDocument()

			' Add an empty worksheet to the file.
			excel.Worksheets.Add("Page 1")
			excel.Worksheets.Add("Page 2")
			Dim worksheet = excel.Worksheets("Page 1")


			' Add hyperlinks into document.
			worksheet.Cells("A1").Value = "External link"
			worksheet.Cells("A1").Hyperlink = New ExcelHyperlink With {
				.Location = "https://sautinsoft.com",
				.ToolTip = "SautinSoft"
			}

			worksheet.Cells("A2").Value = "Internal link"
			worksheet.Cells("A2").Hyperlink = New ExcelHyperlink With {
				.Location = "'Page 2'!A1",
				.ToolTip = "A1 cell on another page"
			}


			' Expand the column to make it look attractive
			worksheet.Columns("A").AutoFit()

			' Saving the excel document.
			excel.Save(outFile)

			' Important for Linux: Install MS Fonts
			' sudo apt install ttf-mscorefonts-installer -y

			' Open the result for demonstration purposes.
			System.Diagnostics.Process.Start(New System.Diagnostics.ProcessStartInfo(outFile) With {.UseShellExecute = True})
		End Sub
	End Class
End Namespace

Download


Если вам нужен пример кода или у вас есть вопрос: напишите нам по адресу support@sautinsoft.ru или спросите в онлайн-чате (правый нижний угол этой страницы) или используйте форму ниже:



Вопросы и предложения всегда приветствуются!

Мы разрабатываем компоненты .Net с 2002 года. Мы знаем форматы PDF, DOCX, RTF, HTML, XLSX и Images. Если вам нужна помощь в создании, изменении или преобразовании документов в различных форматах, мы можем вам помочь. Мы напишем для вас любой пример кода абсолютно бесплатно.