Browse Source

Add support for setting hyperlink display & tooltip (closes #790) (#794)

James Allen 4 years ago
parent
commit
a12dfd3ce6
3 changed files with 25 additions and 1 deletions
  1. 17 1
      cell.go
  2. 7 0
      excelize_test.go
  3. 1 0
      xmlWorksheet.go

+ 17 - 1
cell.go

@@ -431,6 +431,13 @@ func (f *File) GetCellHyperLink(sheet, axis string) (bool, string, error) {
 	return false, "", err
 }
 
+// HyperlinkOpts can be passed to SetCellHyperlink to set optional hyperlink
+// attributes (e.g. display value)
+type HyperlinkOpts struct {
+	Display *string
+	Tooltip *string
+}
+
 // SetCellHyperLink provides a function to set cell hyperlink by given
 // worksheet name and link URL address. LinkType defines two types of
 // hyperlink "External" for web site or "Location" for moving to one of cell
@@ -446,7 +453,7 @@ func (f *File) GetCellHyperLink(sheet, axis string) (bool, string, error) {
 //
 //    err := f.SetCellHyperLink("Sheet1", "A3", "Sheet1!A40", "Location")
 //
-func (f *File) SetCellHyperLink(sheet, axis, link, linkType string) error {
+func (f *File) SetCellHyperLink(sheet, axis, link, linkType string, opts ...HyperlinkOpts) error {
 	// Check for correct cell name
 	if _, _, err := SplitCellName(axis); err != nil {
 		return err
@@ -490,6 +497,15 @@ func (f *File) SetCellHyperLink(sheet, axis, link, linkType string) error {
 		return fmt.Errorf("invalid link type %q", linkType)
 	}
 
+	for _, o := range opts {
+		if o.Display != nil {
+			linkData.Display = *o.Display
+		}
+		if o.Tooltip != nil {
+			linkData.Tooltip = *o.Tooltip
+		}
+	}
+
 	ws.Hyperlinks.Hyperlink = append(ws.Hyperlinks.Hyperlink, linkData)
 	return nil
 }

+ 7 - 0
excelize_test.go

@@ -326,6 +326,13 @@ func TestSetCellHyperLink(t *testing.T) {
 	assert.NoError(t, f.SetCellHyperLink("Sheet2", "C1", "https://github.com/360EntSecGroup-Skylar/excelize", "External"))
 	// Test add Location hyperlink in a work sheet.
 	assert.NoError(t, f.SetCellHyperLink("Sheet2", "D6", "Sheet1!D8", "Location"))
+	// Test add Location hyperlink with display & tooltip in a work sheet.
+	display := "Display value"
+	tooltip := "Hover text"
+	assert.NoError(t, f.SetCellHyperLink("Sheet2", "D7", "Sheet1!D9", "Location", HyperlinkOpts{
+		Display: &display,
+		Tooltip: &tooltip,
+	}))
 
 	assert.EqualError(t, f.SetCellHyperLink("Sheet2", "C3", "Sheet1!D8", ""), `invalid link type ""`)
 

+ 1 - 0
xmlWorksheet.go

@@ -604,6 +604,7 @@ type xlsxHyperlink struct {
 	Ref      string `xml:"ref,attr"`
 	Location string `xml:"location,attr,omitempty"`
 	Display  string `xml:"display,attr,omitempty"`
+	Tooltip  string `xml:"tooltip,attr,omitempty"`
 	RID      string `xml:"http://schemas.openxmlformats.org/officeDocument/2006/relationships id,attr,omitempty"`
 }