### Example Registry Keys for Add-in Installation Source: https://github.com/officedev/office-js-docs-pr/blob/main/docs/publish/publish-office-add-ins-to-appsource.md This example shows concrete registry key entries for installing an add-in named 'ContosoAdd-in' with asset ID 'WA999999999' for Word. ```plaintext // Only the current user. [HKEY_CURRENT_USER\Software\Microsoft\Office\16.0\Wef\AutoInstallAddins\Word\ContosoAdd-in] "AssetIds"="WA999999999" // All users of the computer. [HKEY_LOCAL_MACHINE\Software\Microsoft\Office\16.0\AutoInstallAddins\Word\ContosoAdd-in] "AssetIds"="WA999999999" ``` -------------------------------- ### Start Add-in with npm (Yo Office) Source: https://github.com/officedev/office-js-docs-pr/blob/main/docs/testing/sideload-add-in-with-unified-manifest.md Use this command to build and start your add-in project if your package.json includes a 'start:desktop' script. Ensure the Office application is closed before running. ```bash npm run start:desktop ``` -------------------------------- ### Start Add-in with npm (Default) Source: https://github.com/officedev/office-js-docs-pr/blob/main/docs/testing/sideload-add-in-with-unified-manifest.md Use this command to build and start your add-in project if your package.json does not have a 'start:desktop' script. Ensure the Office application is closed before running. ```bash npm run start ``` -------------------------------- ### Run npm start:desktop for Excel on Windows/Mac Source: https://github.com/officedev/office-js-docs-pr/blob/main/docs/quickstarts/excel-custom-functions-quickstart.md Use this command to start the local web server and load your add-in in Excel on Windows or Mac. This command is used if a 'start:desktop' script exists in your package.json. ```bash npm run start:desktop ``` -------------------------------- ### Run npm start for Excel on Windows/Mac (default) Source: https://github.com/officedev/office-js-docs-pr/blob/main/docs/quickstarts/excel-custom-functions-quickstart.md Use this command to start the local web server and load your add-in in Excel on Windows or Mac. This is the default command if 'start:desktop' is not present in your package.json. ```bash npm run start ``` -------------------------------- ### Get Startup Behavior Source: https://github.com/officedev/office-js-docs-pr/blob/main/docs/develop/run-code-on-document-open.md Retrieves the current startup behavior of the Office Add-in, indicating if it's configured to start automatically. ```APIDOC ## Get the current load behavior There may be scenarios in which your add-in needs to know if it's configured to start automatically the next time the current document is opened. To determine what the current startup behavior is, run the following method, which returns an [Office.StartupBehavior](/javascript/api/office/office.startupbehavior) value. ### Method GET ### Endpoint /api/v1.0/startupBehavior ### Description This endpoint retrieves the current startup behavior of the Office Add-in. ### Response #### Success Response (200) - **behavior** (Office.StartupBehavior) - The current startup behavior of the add-in. ### Response Example ```json { "behavior": "Office.StartupBehavior.Auto" } ``` ``` -------------------------------- ### Start Development Server Source: https://github.com/officedev/office-js-docs-pr/blob/main/docs/develop/configure-your-add-in-to-use-a-shared-runtime.md Run this command in your terminal to start the development server for your Office Add-in. ```command line npm start ``` -------------------------------- ### Configure package.json Scripts Source: https://github.com/officedev/office-js-docs-pr/blob/main/docs/testing/debug-desktop-using-edge-chromium.md Add these scripts to the `scripts` section of your `package.json` file. The `start:desktop` script uses `office-addin-debugging` to start the add-in for desktop debugging, and `dev-server` is used to start your web server. ```json "start:desktop": "office-addin-debugging start $MANIFEST_FILE$ desktop", "dev-server": "$SERVER_START$" ``` -------------------------------- ### Example package.json script for webpack dev server Source: https://github.com/officedev/office-js-docs-pr/blob/main/docs/testing/sideload-add-in-with-unified-manifest.md This script is used to start a local web server for development. Ensure your package.json file includes this script if you are using webpack. ```json { "scripts": { "dev-server": "webpack serve --mode development" } } ``` -------------------------------- ### Start add-in in desktop Excel Source: https://github.com/officedev/office-js-docs-pr/blob/main/docs/excel/custom-functions-debugging.md Use this command to start your add-in in the desktop version of Excel. If the 'start:desktop' script is not available in your package.json, use 'npm run start' instead. ```bash npm run start:desktop ``` ```bash npm run start ``` -------------------------------- ### Install Moment-MSDate Source: https://github.com/officedev/office-js-docs-pr/blob/main/docs/excel/excel-add-ins-ranges-dates.md Install the Moment-MSDate library using npm. This is the first step to enable date conversions in your Excel add-in. ```bash npm install moment-msdate ``` -------------------------------- ### Complete Startup Class Example Source: https://github.com/officedev/office-js-docs-pr/blob/main/docs/tutorials/migrate-vsto-to-office-add-in-shared-code-library-tutorial.md This is a complete example of the `Startup` class after implementing CORS configuration for development. Ensure the `WithOrigins` value matches your development environment's SSL URL. ```csharp public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins"; public IConfiguration Configuration { get; } // NOTE: The following code configures CORS for the localhost:44397 port. // This is for development purposes. In production code, you should update this to // use the appropriate allowed domains. public void ConfigureServices(IServiceCollection services) { services.AddCors(options => { options.AddPolicy(MyAllowSpecificOrigins, builder => { builder.WithOrigins("https://localhost:44397") .AllowAnyMethod() .AllowAnyHeader(); }); }); services.AddControllers(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthorization(); app.UseCors(MyAllowSpecificOrigins); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } } ``` -------------------------------- ### Build and Start Add-in Project Source: https://github.com/officedev/office-js-docs-pr/blob/main/docs/outlook/on-new-compose-events-walkthrough.md Commands to compile the project and launch the local development server for testing the add-in. ```bash npm run build npm start ``` -------------------------------- ### Define base requirements for multiple scopes Source: https://github.com/officedev/office-js-docs-pr/blob/main/docs/develop/understand-requirement-configuration.md Use the 'scopes' property to specify the Office applications where the add-in can be installed. This example shows an add-in installable in both Outlook and Excel. ```json "extensions": [ { "requirements": { "scopes": [ "mail", "workbook" ] } } --- Other child properties of extensions here. ] ``` -------------------------------- ### Get the selected range Source: https://github.com/officedev/office-js-docs-pr/blob/main/docs/excel/excel-add-ins-ranges-get.md Use `getSelectedRange()` to get the range currently selected by the user. This is useful for actions on user-chosen areas. This example logs the address of the selected range. ```javascript await Excel.run(async (context) => { const range = context.workbook.getSelectedRange(); range.load("address"); await context.sync(); console.log(`The address of the selected range is "${range.address}"`); }); ``` -------------------------------- ### Get a named range Source: https://github.com/officedev/office-js-docs-pr/blob/main/docs/excel/excel-add-ins-ranges-get.md Retrieve a range by its defined name using `getRange(namedRange)`. This example gets the range named 'MyRange' from the 'Sample' worksheet and logs its address. ```javascript await Excel.run(async (context) => { const sheet = context.workbook.worksheets.getItem("Sample"); const range = sheet.getRange("MyRange"); range.load("address"); await context.sync(); console.log(`The address of the range "MyRange" is "${range.address}"`); }); ``` -------------------------------- ### Get the entire worksheet range Source: https://github.com/officedev/office-js-docs-pr/blob/main/docs/excel/excel-add-ins-ranges-get.md Use `getRange()` without arguments to get a range representing the entire worksheet. This example logs the address of the entire range for the 'Sample' worksheet. ```javascript await Excel.run(async (context) => { const sheet = context.workbook.worksheets.getItem("Sample"); const range = sheet.getRange(); range.load("address"); await context.sync(); console.log(`The address of the entire worksheet range is "${range.address}"`); }); ``` -------------------------------- ### Start Development Server (Mac) Source: https://github.com/officedev/office-js-docs-pr/blob/main/docs/quickstarts/word-quickstart-yo.md If you are testing on a Mac, run this command to start the local web server before proceeding to sideload the add-in. ```command line npm run dev-server ``` -------------------------------- ### Get a range by address Source: https://github.com/officedev/office-js-docs-pr/blob/main/docs/excel/excel-add-ins-ranges-get.md Use `getRange(address)` to retrieve a specific range when its cell reference is known. This example gets the range B2:C5 from the 'Sample' worksheet and logs its address. ```javascript await Excel.run(async (context) => { const sheet = context.workbook.worksheets.getItem("Sample"); const range = sheet.getRange("B2:C5"); range.load("address"); await context.sync(); console.log(`The address of the range B2:C5 is "${range.address}"`); }); ``` -------------------------------- ### Limit Add-in Installation by Requirement Set Source: https://github.com/officedev/office-js-docs-pr/blob/main/docs/develop/understand-requirement-configuration.md Configure the manifest to control which Office applications and versions an add-in can be installed on. This example shows how to ensure an add-in is installable on both Outlook and Excel, with ribbon controls available only on specific versions supporting Mailbox 1.11 and ExcelApi 1.10 respectively. ```json { "minVersion": "1.10" } ] }, ``` -------------------------------- ### Start Add-in with Office-Addin-Debugging Tool Source: https://github.com/officedev/office-js-docs-pr/blob/main/docs/testing/sideload-add-in-with-unified-manifest.md This command packages the unified manifest and icons into a zip file, sideloads it to the Office application, and starts a local development server. Ensure the Office application is closed before running. ```bash npx office-addin-debugging start desktop ``` -------------------------------- ### Get Appointment End Time (Compose Form) Source: https://github.com/officedev/office-js-docs-pr/blob/main/docs/outlook/get-or-set-the-time-of-an-appointment.md This snippet demonstrates how to retrieve the end time of an appointment being composed in Outlook using the `getAsync` method. It is similar to getting the start time but uses the `item.end` property. ```APIDOC ## GET /api/appointment/end ### Description Retrieves the end time of the appointment currently being composed in Outlook. ### Method GET ### Endpoint `Office.context.mailbox.item.end.getAsync()` ### Parameters #### Query Parameters - **callback** (function) - Required - A function that processes the asynchronous result. It receives an `asyncResult` object. - **asyncContext** (any) - Optional - A user-defined object that is passed to the callback function along with the `asyncResult`. ### Request Example ```javascript Office.context.mailbox.item.end.getAsync(function(asyncResult) { if (asyncResult.status === Office.AsyncResultStatus.Succeeded) { const endTime = asyncResult.value; // Date object console.log('End Time (UTC): ' + endTime.toUTCString()); console.log('End Time (Local): ' + endTime.toLocaleString()); } else { console.error('Error getting end time: ' + asyncResult.error.message); } }); ``` ### Response #### Success Response (200) - **value** (Date) - The end time of the appointment as a JavaScript Date object in UTC format. #### Response Example ```json { "value": "2023-10-27T11:00:00.000Z" } ``` ``` -------------------------------- ### Build and Run Office Add-in Project Source: https://github.com/officedev/office-js-docs-pr/blob/main/docs/tutorials/share-data-and-events-between-custom-functions-and-the-task-pane-tutorial.md Command line instructions to build, start, and stop the development server for the Excel add-in project. ```bash npm run build npm run start npm run stop ``` -------------------------------- ### Get Appointment Start Time (Compose Form) Source: https://github.com/officedev/office-js-docs-pr/blob/main/docs/outlook/get-or-set-the-time-of-an-appointment.md This snippet demonstrates how to retrieve the start time of an appointment being composed in Outlook using the `getAsync` method. It includes error handling and displays the time in both UTC and local formats. ```APIDOC ## GET /api/appointment/start ### Description Retrieves the start time of the appointment currently being composed in Outlook. ### Method GET ### Endpoint `Office.context.mailbox.item.start.getAsync()` ### Parameters #### Query Parameters - **callback** (function) - Required - A function that processes the asynchronous result. It receives an `asyncResult` object. - **asyncContext** (any) - Optional - A user-defined object that is passed to the callback function along with the `asyncResult`. ### Request Example ```javascript Office.context.mailbox.item.start.getAsync(function(asyncResult) { if (asyncResult.status === Office.AsyncResultStatus.Succeeded) { const startTime = asyncResult.value; // Date object console.log('Start Time (UTC): ' + startTime.toUTCString()); console.log('Start Time (Local): ' + startTime.toLocaleString()); } else { console.error('Error getting start time: ' + asyncResult.error.message); } }); ``` ### Response #### Success Response (200) - **value** (Date) - The start time of the appointment as a JavaScript Date object in UTC format. #### Response Example ```json { "value": "2023-10-27T10:00:00.000Z" } ``` ``` -------------------------------- ### Initialize Office Add-in Environment Source: https://github.com/officedev/office-js-docs-pr/blob/main/docs/tutorials/word-tutorial.md Sets up the Office.onReady listener to ensure the add-in is loaded and configured specifically for the Word host environment. ```javascript Office.onReady((info) => { if (info.host === Office.HostType.Word) { document.getElementById("sideload-msg").style.display = "none"; document.getElementById("app-body").style.display = "flex"; } }); ``` -------------------------------- ### Get Applied Sensitivity Label Source: https://github.com/officedev/office-js-docs-pr/blob/main/docs/outlook/sensitivity-label.md Retrieves the GUID of the sensitivity label currently applied to a message or appointment in compose mode. ```javascript Office.context.sensitivityLabelsCatalog.getIsEnabledAsync((asyncResult) => { if (asyncResult.status === Office.AsyncResultStatus.Succeeded && asyncResult.value == true) { Office.context.mailbox.item.sensitivityLabel.getAsync((asyncResult) => { if (asyncResult.status === Office.AsyncResultStatus.Succeeded) { console.log(asyncResult.value); } else { console.log("Action failed with error: " + asyncResult.error.message); } }); } else { console.log("Action failed with error: " + asyncResult.error.message); } }); ``` -------------------------------- ### Initialize Office.js with any framework Source: https://github.com/officedev/office-js-docs-pr/blob/main/docs/develop/connect-to-javascript-frameworks.md Use this universal pattern to ensure Office.js is ready before initializing your application framework. ```typescript // Universal pattern - works with any framework. Office.onReady((info) => { // Office.js is now ready. // Initialize your framework here. initializeYourFramework(); }); ``` -------------------------------- ### Export Chart as Image Source: https://github.com/officedev/office-js-docs-pr/blob/main/docs/excel/excel-add-ins-charts.md This example demonstrates how to get a Base64-encoded string of a chart as a JPEG image. The image can then be used outside of Excel. ```APIDOC ## Chart.getImage ### Description Exports a chart as a Base64-encoded JPEG image string. This is useful for reusing charts outside of Excel, such as in web pages or reports. ### Method Signature ```typescript getImage(width?: number, height?: number, fittingMode?: Excel.ImageFittingMode): OfficeExtension.ClientResult; ``` ### Parameters * **width** (number) - Optional. The desired width of the image. * **height** (number) - Optional. The desired height of the image. * **fittingMode** (Excel.ImageFittingMode) - Optional. Specifies how the chart should be scaled to fit the specified dimensions. Possible values are: * `Fill`: The image's minimum height or width is the specified height or width, whichever limit is reached first during scaling. This is the default behavior. * `Fit`: The image's maximum height or width is the specified height or width, whichever limit is reached first during scaling. * `FitAndCenter`: The image's maximum height or width is the specified height or width, whichever limit is reached first during scaling. The resulting image is centered relative to the other dimension. ### Request Example ```javascript await Excel.run(async (context) => { const chart = context.workbook.worksheets.getItem("Sheet1").charts.getItem("Chart1"); const imageAsString = chart.getImage(300, 200, Excel.ImageFittingMode.Fit); await context.sync(); console.log(imageAsString.value); // The imageAsString.value contains the Base64-encoded JPEG string. }); ``` ### Response * **value** (string) - A Base64-encoded string representing the chart as a JPEG image. ``` -------------------------------- ### Get the selected range in Excel Source: https://github.com/officedev/office-js-docs-pr/blob/main/docs/excel/excel-add-ins-workbooks.md Use getSelectedRange() when your add-in works with the user's current selection. If multiple ranges are selected, the method throws an InvalidSelection error. The next example gets the selected range and sets its fill color to yellow. ```javascript await Excel.run(async (context) => { const range = context.workbook.getSelectedRange(); range.format.fill.color = "yellow"; await context.sync(); }); ``` -------------------------------- ### Initialize framework-specific applications Source: https://github.com/officedev/office-js-docs-pr/blob/main/docs/develop/connect-to-javascript-frameworks.md Examples of initializing various JavaScript frameworks within the Office.onReady callback. ```typescript // src/index.tsx Office.onReady(() => { const root = ReactDOM.createRoot(document.getElementById('root')); root.render(); }); ``` ```typescript // src/main.ts Office.onReady(() => { platformBrowserDynamic() .bootstrapModule(AppModule) .catch(err => console.error(err)); }); ``` ```typescript // src/main.ts Office.onReady(() => { createApp(App).mount('#app'); }); ``` ```typescript // src/main.ts Office.onReady(() => { new App({ target: document.getElementById('app') }); }); ``` -------------------------------- ### Run npm start for Excel on the web Source: https://github.com/officedev/office-js-docs-pr/blob/main/docs/quickstarts/excel-custom-functions-quickstart.md Use this command to start the local web server for testing your add-in in Excel on the web. Replace {url} with the URL of an Excel document. ```bash npm start -- --document {url} ``` -------------------------------- ### Basic Copy Operation Source: https://github.com/officedev/office-js-docs-pr/blob/main/docs/excel/excel-add-ins-ranges-cut-copy-paste.md This example demonstrates a basic copy operation, copying data from range A1:E1 to the range starting at G1. ```APIDOC ## Basic copy operation The following code sample copies the data from **A1:E1** into the range starting at **G1** (which ends up pasting into **G1:K1**). ```javascript await Excel.run(async (context) => { let sheet = context.workbook.worksheets.getItem("Sample"); // Copy everything from "A1:E1" into "G1" and the cells afterwards ("G1:K1"). sheet.getRange("G1").copyFrom("A1:E1"); await context.sync(); }); ``` ``` -------------------------------- ### Initialize First-Run Experience in Office Add-ins Source: https://github.com/officedev/office-js-docs-pr/blob/main/docs/tutorials/first-run-experience-tutorial.md This code initializes the Office add-in, checks local storage for the 'showedFRE' key, and displays the first-run experience if the key is missing. It also defines the function to show the experience and persist the state to local storage. ```javascript Office.onReady((info) => { if (info.host === Office.HostType.Excel) { document.getElementById("sideload-msg").style.display = "none"; document.getElementById("app-body").style.display = "flex"; // showedFRE is created and set to "true" when you call showFirstRunExperience(). if (!localStorage.getItem("showedFRE")) { showFirstRunExperience(); } document.getElementById("run").onclick = run; } }); function showFirstRunExperience() { document.getElementById("first-run-experience").style.display = "flex"; localStorage.setItem("showedFRE", "true"); } ``` -------------------------------- ### Get Appointment Start Time in Outlook Add-in (JavaScript) Source: https://github.com/officedev/office-js-docs-pr/blob/main/docs/outlook/get-or-set-the-time-of-an-appointment.md Retrieves the start time of an appointment being composed in an Outlook add-in. This function uses the `getAsync` method of the `item.start` property, which is available only in compose forms. The callback function handles the asynchronous result, extracting the start time as a UTC `Date` object or logging any errors. It also displays the time in both UTC and local formats. ```javascript let item; // Confirms that the Office.js library is loaded. Office.onReady((info) => { if (info.host === Office.HostType.Outlook) { item = Office.context.mailbox.item; getStartTime(); } }); // Gets the start time of the appointment being composed. function getStartTime() { item.start.getAsync((asyncResult) => { if (asyncResult.status === Office.AsyncResultStatus.Failed) { write(asyncResult.error.message); return; } const startTime = asyncResult.value; // Display the start time in UTC format on the page. write(`The start time in UTC is: ${startTime.toUTCString()}`); // Display the start time in local time on the page. write(`The start time in local time is: ${startTime.toLocaleString()}`); }); } // Writes to a div with id="message" on the page. function write(message) { document.getElementById("message").innerText += message; } ``` -------------------------------- ### Get Pages in Current Section Source: https://github.com/officedev/office-js-docs-pr/blob/main/docs/onenote/onenote-add-ins-programming-overview.md Retrieves and logs the ID and title of each page in the currently active OneNote section. This example demonstrates the load/sync pattern for interacting with OneNote objects. ```javascript async function getPagesInSection() { await OneNote.run(async (context) => { // Get the pages in the current section. const pages = context.application.getActiveSection().pages; // Queue a command to load the id and title for each page. pages.load('id,title'); // Run the queued commands, and return a promise to indicate task completion. await context.sync(); // Read the id and title of each page. $.each(pages.items, function(index, page) { let pageId = page.id; let pageTitle = page.title; console.log(pageTitle + ': ' + pageId); }); }); } ``` -------------------------------- ### Navigate to Project Directory Source: https://github.com/officedev/office-js-docs-pr/blob/main/docs/quickstarts/excel-quickstart-react.md Change to the root folder of your newly created add-in project. ```command line cd "My Office Add-in" ``` -------------------------------- ### Start local web server and test in Excel on the web Source: https://github.com/officedev/office-js-docs-pr/blob/main/docs/tutorials/excel-tutorial.md Use this command to start the local web server for testing your add-in in Excel on the web. Remember to replace '{url}' with the actual URL of your Excel document. ```command line npm start -- --document "{url}" ``` -------------------------------- ### Get the used range Source: https://github.com/officedev/office-js-docs-pr/blob/main/docs/excel/excel-add-ins-ranges-get.md Retrieve the smallest range containing data or formatting with `getUsedRange()`. If the worksheet is blank, it returns the top-left cell. This example logs the address of the used range. ```javascript await Excel.run(async (context) => { const sheet = context.workbook.worksheets.getItem("Sample"); const range = sheet.getUsedRange(); range.load("address"); await context.sync(); console.log(`The address of the used range in the worksheet is "${range.address}"`); }); ``` -------------------------------- ### Set Placeholder Message for Encrypted Email Body Source: https://github.com/officedev/office-js-docs-pr/blob/main/docs/outlook/encryption-decryption.md Use this method to set the placeholder message for the body of an encrypted email. This message guides users on how to install your add-in if they don't have it. ```javascript // Call Office.context.mailbox.item.body.setAsync to set the message body during the encryption process. Office.context.mailbox.item.body.setAsync("Placeholder message for encrypted email."); ``` -------------------------------- ### Initialize with a Callback Function Source: https://github.com/officedev/office-js-docs-pr/blob/main/docs/develop/initialize-add-in.md Use this method to perform initialization tasks based on the host and platform. The callback receives an info object containing host and platform details. ```javascript Office.onReady(function(info) { if (info.host === Office.HostType.Excel) { // Do Excel-specific initialization (for example, make add-in task pane's // appearance compatible with Excel "green"). } if (info.platform === Office.PlatformType.PC) { // Make minor layout changes in the task pane. } console.log(`Office.js is now ready in ${info.host} on ${info.platform}`); }); ``` -------------------------------- ### Add an Image from a Local File Source: https://github.com/officedev/office-js-docs-pr/blob/main/docs/excel/excel-add-ins-shapes.md Use `ShapeCollection.addImage` to insert a JPEG or PNG image from a local file. The image must be provided as a Base64-encoded string. This example uses `FileReader` to get the Base64 data. ```javascript const myFile = document.getElementById("selectedFile"); const reader = new FileReader(); reader.onload = () => { Excel.run(async (context) => { const startIndex = reader.result.toString().indexOf("base64,"); const myBase64 = reader.result.toString().substring(startIndex + 7); const sheet = context.workbook.worksheets.getItem("MyWorksheet"); const image = sheet.shapes.addImage(myBase64); image.name = "Image"; await context.sync(); }).catch(errorHandlerFunction); }; reader.readAsDataURL(myFile.files[0]); ``` -------------------------------- ### Stop and Start Local Web Server (npm) Source: https://github.com/officedev/office-js-docs-pr/blob/main/docs/tutorials/outlook-tutorial.md These commands are used to manage the local web server for the Office add-in. 'npm stop' is used to halt the currently running server, and 'npm start' is used to restart the server and automatically sideload the add-in, applying any manifest changes. ```bash npm stop ``` ```bash npm start ```