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

This commit is contained in:
James Allen 2021-03-03 12:30:31 +00:00 committed by GitHub
parent 7ef1892f32
commit a12dfd3ce6
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 25 additions and 1 deletions

18
cell.go
View File

@ -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
}

View File

@ -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 ""`)

View File

@ -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"`
}