能否为Office Add-ins添加类似VSTO的UI按钮?
Absolutely! Let’s break down your questions clearly:
Can you add VSTO-style buttons to the Office Add-ins UI?
Yes, you absolutely can add custom buttons (and other ribbon controls) to the Office ribbon, just like you would with VSTO. The key difference is that instead of using .NET code to define the ribbon, you configure it via your add-in's manifest file—an XML document that outlines your add-in's structure, permissions, and UI elements.
For example, here’s a snippet of a manifest that adds a custom tab with a functional button:
<CustomTab id="MyCustomTab"> <Group id="MyCustomGroup"> <Label resid="MyGroupLabel" /> <Button id="MyCustomButton"> <Label resid="MyButtonLabel" /> <Supertip> <Title resid="MyButtonTitle" /> <Description resid="MyButtonDesc" /> </Supertip> <Icon> <bt:Image size="16" resid="Icon16" /> <bt:Image size="32" resid="Icon32" /> <bt:Image size="80" resid="Icon80" /> </Icon> <Action xsi:type="ExecuteFunction"> <FunctionName>handleButtonClick</FunctionName> </Action> </Button> </Group> <Label resid="MyTabLabel" /> </CustomTab>
Tools like the Yeoman Office Generator can scaffold add-ins with pre-configured ribbon controls, so you don’t have to write all the XML from scratch.
Does Office Add-ins support setting button functionality?
Definitely! Every ribbon button you add can be linked to a custom JavaScript (or TypeScript) function that triggers when the button is clicked. These functions can handle all kinds of tasks:
- Manipulate the Office document (e.g., insert text, format Excel cells, add Word paragraphs)
- Open your add-in’s task pane
- Show a custom dialog box
- Call external APIs (with proper permission configuration)
Here’s a simple example of a button click handler in JavaScript:
function handleButtonClick(event) { // Example: Open a custom dialog Office.context.ui.displayDialogAsync( './dialog.html', { height: 40, width: 50 }, (result) => { // Handle dialog interactions here } ); // Notify Office that the function completed successfully event.completed(); }
Just make sure your function is exposed in your add-in’s script file, and the manifest correctly references the function name (as shown in the XML snippet above).
A quick bonus note: Unlike VSTO (which is desktop-only), Office Add-ins work across desktop Office, Office Online, and mobile Office apps—so your ribbon buttons and their functionality will be available wherever your users access Office.
内容的提问来源于stack exchange,提问作者MirrorMirror

