Giter VIP home page Giter VIP logo

office-js-snippets's Introduction

Office JS Snippets

A collection of code snippets built with Script Lab

Script Lab import gallery screenshot

To contribute:

Note: For all command line interface (CLI) commands mentioned in these instructions, you can use either Git Bash or a Node Command Prompt.

One-time tasks

  1. Fork this project into your GitHub account.
  2. Clone your fork to your development computer.
  3. Ensure that you have Node, version 6.10+, installed. (To check the version run the command node -v.)
  4. Install yarn as a global package npm install yarn --global.
  5. Be sure your CLI is in the root of the office-js-snippets repo and run yarn install. (It is similar to npm install.)
  6. Set up the original \OfficeDev\office-js-snippets as the upstream repo for your local repo by following the steps in Configuring a remote for a fork.
  7. If you'll be using Visual Studio Code as your editor, install the TSLint extension for Visual Studio Code.

Adding a new sample

For the git tasks in this procedure, the instructions assume that you're using a CLI. You are welcome to use a GUI git client. Consult the client's help to learn how to carry out the same tasks.

  1. Create a snippet using Script Lab. Ensure that the name and description are what you want to be shown publicly. Use standard TypeScript indentation. Improper indentation can cause a failure of the build that you run in a later step. See also the Style guidelines section below.

  2. Choose the Share icon, and then choose Copy to Clipboard.

  3. Paste the contents into a text editor.

  4. Near the top of the file, you will see the line api_set: {}. This needs to be changed to specify the host API version of the most recently added API that is used in your snippet. For example, if the snippet is for Excel and it uses some APIs that were introduced in Excel API 1.3, some in 1.4, and some in 1.5, then you need to specify ExcelApi 1.5 as the value of the api_set property. Put a line break and four spaces before the value and no {} characters. To continue the example, when you're done the property would look like this:

    api_set:
        ExcelApi: '1.5'
  5. Check the name and description property values, also near the top of the file, and edit as needed.

  6. Save the file somewhere outside of the office-js-snippets project. (You will move it into the project in a later step.) The file name must have a ".yaml" extension and it must be in kebab-case. For examples, see the existing *.yaml files in the subfolders of the samples folder of the project.

  7. Make sure the main branch of your fork is in sync with the main branch of the upstream \OfficeDev\office-js-snippets repo by following the steps in Syncing a fork.

  8. Create a new branch at the office-js-snippets root folder of your local repo by running the command git checkout -b {name_of_your_new_branch}. (This will create and checkout the new branch. Stay in this branch for all the remaining steps.) Each snippet should have its own branch. Suggestion: use the name of the yaml file that you created above (without the extension) as the branch name.

  9. Decide the folder where your snippet should be added. All snippet files must reside within the appropriate subfolder inside the samples folder. Within the samples folder, the structure of subfolders is as follows:

    • The base folders such as excel, word, etc. primarily represent the various host applications.
    • Within each base folder, group folders organize snippets into various categories.
    • Within each group folder, each .yaml file represents a snippet.

    Note: If your snippet doesn't fit with any existing group folder, create a new group folder inside the base folder. If the existing folders in the base folder begin with numbers, such as 03-range, then your new folder should also begin with a number. Since the numbers determine the sequence of the groups in Script Lab, use a number between the numbers of the groups between which you want the new folder to appear.

  10. Open one of the .yaml files already in the group folder. If it has an order property near the top, then the snippets in the group folder are ordered in a particular sequence in Script Lab. Add an order property to the top of your .yaml file and give it a number that is between the order numbers of the snippets between which you want it to appear.

  11. Copy your .yaml file to the chosen group folder.

  12. Run yarn start. If there are no problems, the output will end with a Done!. If there are errors, review the output to check what caused the build validation to fail, and fix as needed. See Known errors and fixes for more information.

    Note: The yarn start command adds an id property to the top of the file.

  13. Re-run yarn start, and fix errors, until the build succeeds.

  14. Run git status. You should see that, in addition to your new .yaml file (or possibly new folder), a playlist\{host}.yaml file (where {host} is excel, word, etc.) has also been changed. This is expected. The build tool you just ran added a reference to your new snippet to this file.

  15. Run the following two commands. The commit message should be a brief description of what the snippet demonstrates; for example, "shows how to use getWhatever method".

    git add -A
    git commit -m "{commit message}"
    
  16. Push the snippet to your fork by running:

    git push --set-upstream origin {name_of_your_new_branch}
    
  17. You now create a pull request. In your fork on GitHub, switch to your new branch.

  18. Choose New pull request.

  19. On the Open a pull request page, verify that:

    • the base fork is OfficeDev/office-js-snippets
    • the base branch is main
    • the head fork is {your-GitHub-account}/office-js-snippets
    • the "compare" branch is {name_of_your_new_branch}.
  20. The title of the pull request defaults to your commit message. Change it as needed and optionally add a comment to provide additional information about the pull request to the reviewers.

  21. All pull requests to office-js-snippets must be approved by at least one reviewer. On the right side of the page is a Reviewers section. You can optionally suggest one or more people to review the pull request. (GitHub sometimes lists one or more admins of the repo by default, but it is not consistent in doing this.) Your pull request will be reviewed even if you don't suggest anyone.

  22. Choose Create pull request. The page for your pull request will open. There will initially be a message on the page saying Some checks haven’t completed yet. An online version of the same build tool that you ran locally is testing the files again. It usually takes a few minutes.

    Note: Since your pull request passed locally, it should pass the online test too. Once in a while, the online test fails when the local test passed. This is usually a bug in the online test service. If this happens, cancel the pull request, wait a few hours, and then repeat the steps for creating a pull request.

  23. The reviewers may make comments on your pull request and ask you to make changes. Make changes in Script Lab and then repeat the process of creating the .yaml file. You do not have to create the new branch again, but make sure it is checked out when you copy the changed .yaml file over the previous version. After you commit and push the changed version to your fork, the new version is automatically added to your existing pull request. Do not create a new pull request.

  24. When the reviewers are satisfied, your pull request will be merged to the main branch and the pull request will be closed.

    Note: In a few days, the repo admins will merge your snippet into the prod branch. It will then appear in Samples area of Script Lab. (It is in the My Snippets area as soon as you create it.)

  25. Optionally, you can delete the branch you created from your fork and/or your local clone.

Known errors and fixes in the build tool

  • An error saying that name has upper-case letters or other disallowed characters is not referring to the name property in the file. It is referring to the file name itself. You'll also get this error, if the file extension is not .yaml.

Style guidelines

Basic snippet structure is as follows:

$("#run").on("click", () => tryCatch(run));

async function run() {
    await Word.run(async (context) => {
        const range = context.document.getSelection();
        range.font.color = "blue";

        await context.sync();
    });
}

/** Default helper for invoking an action and handling errors. */
async function tryCatch(callback) {
    try {
        await callback();
    }
    catch (error) {
        OfficeHelpers.UI.notify(error);
        OfficeHelpers.Utilities.log(error);
    }
}

A few style rules to observe:

  • Use standard TypeScript indentation.
  • For each button, define a corresponding async function to be run when the button is clicked. The async function can be called "run" if there is only one button on the page -- otherwise, name it as you will.
  • Each button-click handler should invoke the tryCatch function, passing in the name of the async function to be executed when the button is clicked.
  • All HTML IDs should be all-lower-case-and-hyphenated.
  • Unless you are explicitly showing pretty UI, you don't have to do the popup notification except for one or two samples. It's a lot of HTML & JS code, and also not strictly Fabric-y (there is a more "correct" way of doing this with components).
  • Strings should be in double-quotes.
  • Don't forget the semicolons.
  • Libraries in snippets must have a specific version. Eg. [email protected].

Debugging the build script

  • The scripts for building/validating the snippets are under the config folder -- in particular, under build.ts.

Note: If debugging in Visual Studio Code, you can use "F5" to attach the debugger, but be sure to run npm run tsc before you do (and after any code change!). F5 is not set to recompile!

Join the Microsoft 365 Developer Program

Join the Microsoft 365 Developer Program to get resources and information to help you build solutions for the Microsoft 365 platform, including recommendations tailored to your areas of interest.

You might also qualify for a free developer subscription that's renewable for 90 days and comes configured with sample data; for details, see the FAQ.


This project has adopted the Microsoft Open Source Code of Conduct. For more information, see the Code of Conduct FAQ or contact [email protected] with any additional questions or comments.

office-js-snippets's People

Contributors

alexanderzlatkovski avatar alexjerabek avatar alison-mk avatar annich-ms avatar cakriwut avatar cshashwat avatar danielebercovici avatar davidchesnut avatar dependabot[bot] avatar elizabethsamuel-msft avatar emtencza avatar grant avatar hongbo-miao avatar jakobpn avatar juanelojuanelo avatar kbrandl avatar lindalu-msft avatar microsoft-github-policy-service[bot] avatar ndeleuze avatar nico-bellante avatar oleg-o avatar reezaali avatar rick-kirkham avatar samantharamon avatar saunders77 avatar tdslinden avatar timwan10 avatar umasubra avatar wrathofzombies avatar zlatkovsky avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

office-js-snippets's Issues

Sort Table Data snippet uses inappropriate Sort object

The Sort table data snippet gets a reference to the table's data range and then passes the SortField to the apply method of the Range.Sort object. Presumably, this is intended to exclude the header row from the range to be sorted. But this is an unnecessary complication. There is also a Table.Sort object whose apply method is smart enough to exclude the header row.

Modify "gradients" sample to make use of setCellProperties

I've seen two questions on StackOverflow about getting or setting cell properties in bulk, the most recent of which was yesterday: https://stackoverflow.com/questions/56755657/how-does-the-range-function-getcellproperties-in-the-javascript-excel-api-work.

The “Just for Fun -> Gradient” sample would be trivially convertible to make use of the setCellProperties API, and would run an order of magnitude faster than it does today (or faster still on larger sizes).

You could even make it be two different helper functions, that are redirected to based on whether isSetSupported("ExcelApi", 1.9) is true.

I'm happy to review the PR.

  • Michael

Get image from PowerPoint document

Hello, thanks for your work and your samples.

I don't know if it's an appropriate spot for my questions but here it is:

How one is supposed to get image from a PowerPoint file ?

getSelectedDataSync returns an error when an image is selected. Reading the docs it seems like it is not possible by any of the provided function.

So, is it even possible ?

Thanks :)

Outlook Add-in Compose - Dynamic Control Button Text Updating

I developed an add-in built with yo generator (Node.js) that works as a configurator which enables the outlook compose to enable/disable sending a copy of the new email to a custom url on-send.

There's a control button added that says 'Toggle Send to cCRM' but I would prefer a toggle text dynamically from 'Enable send to cCRM' to 'Disable send to cCRM' and vice-versa when clicking the control button to improve UI experience. Is it possible to accomplish?

Error with "Find text matches within a range", Excel.SearchDirection doesn't exist in release version

This doesn't appear to impact running Script Lab, but the error is off-putting.

Bug Report

  • Host: Excel
  • OS: Windows
  • Browser: Win32
  • Environment: Beta

Steps to Reproduce:

  1. Open Code pane.
  2. Open the "Find text matches within a range" sample.
  3. Open the Run pane.

Failure Logs:

"Unable to get property 'forward' of undefined or null reference",
"https://script-lab-react-runner-beta.azurewebsites.net/",
117,
1,
TypeError: Unable to get property 'forward' of undefined or null reference
]

Screenshot:

image

onSelectionChanged event - sample request

I have not idea if here it is the correct site, but I would like to know if onSelectionChanged event still is in BETA version or already is available. I would like to use it but I don't find any example.
BR!


Document Details

Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.

Getting range from argument example

I am trying to write a custom function in scriptlab to check if a value is in a selected range, however I cannot seem to figure out how to actually accept that range as the function argument. The example function I have created is below (where I thought range would equal something like "A1:D1"):

/** @CustomFunction */
async function exists(range): any {
    const sheet = context.workbook.worksheets.getActiveWorksheet()
    sheet.getRange(range)
...
}

This however results in a $CALC! error. Any tips or ideas?

Identifier a cell in excel

Hello,
For our project is necessary can identifier a cell of excel (for example through a Id, tag or similar)

We are using the cell position for assign a name to one table. If add or delete a column in the sheet the cell position change and we are not able identifier the tableName.

how can we set/get a property unique for the cell?

Best Regards

PowerPoint Shapes API preview bug when working with multiple shapes

This issue occurs in PowerPoint when running the "Insert shape, line, and text box" sample in Script lab. Sample code is here: https://github.com/OfficeDev/office-js-snippets/blob/main/samples/powerpoint/preview-apis/shapes.yaml

If you are on a slide with multiple shapes the code can get confused when shrinking or moving the hexagon. It can end up grabbing a different element and applying incorrect settings. Need to ensure it can correctly identity and use the hexagon.

Repo steps:

  1. Open PowerPoint on desktop and a new presentation. You will get a blank slide with title and subtitle.
  2. Open Script lab and run the sample.
  3. Choose "Create hexagon".
  4. Choose "Shrink hexagon". At this point the title will get shrunk, not the hexagon.
  5. Choose "Move hexagon". Again the title is moved, but not the hexagon.

Bug in Find text matches within a range

It appears the example has a bug, it always searches for “Groceries”, whatever value one enters in the text-box.

If I change this:

searchRange.find($("#searchText").text(), {

to

searchRange.find($("#searchText").val().toString(), {

the example works as expected.

Unable to call fetch

I'm unable to call fetch and can't find documentation regarding web calls. I assume you have to import fetch in libraries but I can't figure out how.

Reorganize libraries tab

Right now the split between JS libraries and their types -- esp. for Office.js reference -- is making it really hard to switch versions.

Reorganizing the libraries.

Will first do this for default template, we can then do it for the rest.

EWS SOAP request to fetch ICalUid

Since Office JS does not provide ICalUid as a parameter, could you publish a snippet on how to fetch it from the Office.context.mailbox.item.itemId using makeEwsRequestAsync?

Something like:

var ewsId = Office.context.mailbox.item.itemId;
var request = '<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages" xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">' +
    '  <soap:Header><t:RequestServerVersion Version="Exchange2013" /></soap:Header>' +
    '  <soap:Body>' +
    '    <m:GetItem>' +
    '      <m:ItemShape>' +
    '        <t:BaseShape>IdOnly</t:BaseShape>' +
    '      </m:ItemShape >' +
    '      <m:ItemIds>' +
    '        <t:ItemId Id="' + ewsId + '" />' +
    '      </m:ItemIds>' +
    '    </m:GetItem>' +
    '  </soap:Body>' +
    '</soap:Envelope>';

Office.context.mailbox.makeEwsRequestAsync(request, function (result) {
    console.log(result.value);
});

Pivot Table Samples are broken

Bug Report

  • Host: Excel
  • OS: Windows 10
  • Browser: N/A
  • Environment: PROD

Expected behavior:

In Desktop Version of Excel, running Pivot Table Samples should work

Actual behavior:

The steps where Pivot Table APIs are invoked, the samples crash with the following error
Rich API Error. AccessDenied. You cannot perform the requested Operation.

Please note:, there is absolutely no issue when the samples are run in Web version of Excel

Steps to Reproduce:

  1. Run Desktop version of Excel
  2. Launch ScriptLab Add-in
  3. Click on "Samples" and enter "Pivot" in Search box
  4. Click on "Create and Modify" Sample to run it
  5. From the "Run" menu, click on "Run In this Pane"
  6. Click on "Setup Sample" button
    7.Next click on "Create" button. This results in the AccessDenied error logged to the Console

Failure Logs:

c {name: "RichApi.Error", code: "AccessDenied", traceMessages: Array[0], innerError: null, debugInfo: Object}
name: "RichApi.Error"
code: "AccessDenied"
traceMessages: Array[0]
innerError: null
▶debugInfo: Object
code: "AccessDenied"
message: "You cannot perform the requested operation."
toString: function ()
errorLocation: "PivotTableCollection.add"
statement: "var add=pivotTables.add(...);"
▶surroundingStatements: Array[9]
0: "..."
1: "var worksheet1=worksheets.getItem(...);"
2: "var range1=worksheet1.getRange(...);"
3: "// Instantiate {range1}"
4: "var worksheet2=worksheets.getItem(...);"
5: "var pivotTables=worksheet2.pivotTables;"
6: "// >>>>>"
7: "var add=pivotTables.add(...);"
8: "// <<<<<"
▶fullStatements: Array[1]

image

JS Office Outlook add-in: get email as a file

Hello,

Maybe it's irrelevant for these snippets set, but is it possible to get whole email as a file or just collect all email data using office javascript package? I didn't find any similar method in reference:
https://dev.office.com/reference/add-ins/outlook/1.5/Office?product=outlook&version=v1.5
But it is possible to get all email data (body, cc, etc.) one by one, is it the only way?

I know it is possible to do so using Microsoft Exchange and email id and access token, but I can't share access tokens due to security requirements.

Thank you!

Basic shared API snippet doesn't work in Excel

The Excel snippet "Basic API Call (Office 2013)" throws "Invalid API call in the current context" when I have some (or all) text in a cell selected. Same error if I have the cell selected.

Request for another Fabric example

I've looked through the Fabric JS - Using form data word sample a few times, but I'm having a real hard time merging the concepts there with the documentation and snippets found on the Fabric site ( https://developer.microsoft.com/en-us/fabric#/components/list ). Would be great to get something with a bit more focus on how to create UI elements properly in Script Lab and use them. Especially noting how it might be different from creating the component and using it in a standard office-js React add-in.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.