如何使用 office-js 以编程方式将超链接添加到工作表中的单元格?

How to programatically add a hyperlink to a cell in a worksheet using office-js?

我正在开发一个 Excel 加载项,使用 JavaScript API 构建加载项 Excel 2016。

我遇到的问题是没有将 url/link 放在单元格中 - 我宁愿让这个 url 可点击(你可能知道在 url 中输入 url一个单元格并点击 ).

在 VBA 中,解决方案是这样的(例如):

With Worksheets(1)
    .Hyperlinks.Add .Range("E5"), "http://example.microsoft.com"
End With

很遗憾,我在JavaScriptAPI中找不到超链接功能。 有什么想法吗?

非常感谢您的帮助和最诚挚的问候 埃里克

Excel 中有两种类型的超链接,一种是在 VBA 到 Hyperlinks.add 中创建的,另一种是通过公式创建的。 Excel JavaScript 对象模型很容易支持后者。

Excel.run(function (ctx) {
    var firstCellInSelection = ctx.workbook.getSelectedRange().getCell(0, 0);
    firstCellInSelection.formulas = [['=HYPERLINK("http://www.bing.com")']];
    return ctx.sync();
}).catch(function (error) {
    console.log(error);
});

~ Michael Zlatkovsky,Office 可扩展性团队开发人员,MSFT

OfficeJS 测试版中现在可以添加超链接。 您可以使用...加载测试版...

<script type="text/javascript" src="https://appsforoffice.microsoft.com/lib/beta/hosted/Office.js"></script>

...和 ​​get/set 超链接

在单元格 A1 中设置超链接:

Excel.run((context) => {
    const sheet = context.workbook.worksheets.getActiveWorksheet();
    const range = sheet.getRange('A1');
    range.hyperlink = {
        address: `mailto:test@example.com`,
        documentReference: null,
        screenTip: null,
        textToDisplay: 'Send me a Mail!',
    };
    return context.sync();
 })

从单元格 A1 获取超链接:

Excel.run((context) => {
    const sheet = context.workbook.worksheets.getActiveWorksheet();
    const range = sheet.getRange('A1').load('values, hyperlink');
    return context.sync().then(() => console.log(range.hyperlink));
})

API参考