### Create Filled Radar Chart in Excel Script Source: https://github.com/officedev/office-scripts-docs/blob/main/docs/resources/samples/chart-samples.md This example demonstrates how to create a filled radar chart, useful for visualizing performance against targets. The data should be ordered with target values preceding current values. ```TypeScript function main(workbook: ExcelScript.Workbook) { const sheet = workbook.getActiveWorksheet(); // Add sample data - Target first, then Current so Current is drawn on top. const data = [ ["Category", "Target", "Current"], ["Customer Satisfaction", 9.0, 7.5], ["Product Quality", 9.5, 8.2], ["Delivery Speed", 9.0, 6.8], ["Price Competitiveness", 8.5, 7.0], ["Innovation", 9.5, 8.5], ["Market Presence", 9.0, 7.2] ]; const dataRange = sheet.getRange("A1:C7"); dataRange.setValues(data); // Create filled radar chart. const chart = sheet.addChart( ExcelScript.ChartType.radarFilled, dataRange ); chart.setPosition("D1"); chart.getTitle().setText("Performance vs Target Metrics"); chart.getLegend().setPosition(ExcelScript.ChartLegendPosition.bottom); } ``` -------------------------------- ### Create a Scatter with Smooth Lines (No Markers) Chart Source: https://github.com/officedev/office-scripts-docs/blob/main/docs/resources/samples/chart-samples.md This example generates a scatter chart with smooth connecting lines and no data point markers. It uses sample input and output data. ```TypeScript function main(workbook: ExcelScript.Workbook) { const sheet = workbook.getActiveWorksheet(); // Add sample data. const data = [ ["Input", "Output"], [1, 5], [2, 12], [3, 22], [4, 35], [5, 51], [6, 70], [7, 92] ]; const dataRange = sheet.getRange("A1:B8"); dataRange.setValues(data); // Create scatter chart with smooth lines but no markers. const chart = sheet.addChart( ExcelScript.ChartType.xyscatterSmoothNoMarkers, dataRange ); chart.setPosition("D1"); chart.getTitle().setText("Response Curve Analysis"); chart.getLegend().setVisible(false); } ``` -------------------------------- ### Create 3D Surface Chart with Excel Script Source: https://github.com/officedev/office-scripts-docs/blob/main/docs/resources/samples/chart-samples.md Generates a 3D surface chart to visualize trends across two dimensions, useful for finding optimal combinations. This example uses sample temperature data. ```TypeScript function main(workbook: ExcelScript.Workbook) { const sheet = workbook.getActiveWorksheet(); // Add sample data (temperature at different coordinates). const data = [ ["", "0", "5", "10", "15", "20"], ["0", 20, 22, 25, 28, 30], ["5", 22, 24, 27, 30, 32], ["10", 25, 27, 30, 33, 35], ["15", 28, 30, 33, 36, 38], ["20", 30, 32, 35, 38, 40] ]; const dataRange = sheet.getRange("A1:F6"); dataRange.setValues(data); // Create surface chart. const chart = sheet.addChart( ExcelScript.ChartType.surface, dataRange ); chart.setPosition("A8"); chart.getTitle().setText("Temperature Distribution (3D Surface)"); chart.getLegend().setPosition(ExcelScript.ChartLegendPosition.right); } ``` -------------------------------- ### Run Script to Write Data Source: https://github.com/officedev/office-scripts-docs/blob/main/docs/resources/samples/write-large-dataset.md Use the 'Run script' action to write the data read in the previous step to a target Excel file. Ensure to switch the 'data' input to 'entire array' and specify the start row and batch size. ```Power Automate Excel Online (Business) - Run script Location: OneDrive for Business Document Library: OneDrive File: "TargetWorkbook.xlsx" Script: Write data at row location data: result (dynamic content from Read data) [Switch input to entire array] startRow: currentRow (dynamic content) batchSize: batchSize (dynamic content) ``` -------------------------------- ### Create Region Map Chart Source: https://github.com/officedev/office-scripts-docs/blob/main/docs/resources/samples/chart-samples.md Creates a region map chart to visualize data across geographical areas. This example uses state names and sales figures, setting the chart position, title, and legend. ```TypeScript function main(workbook: ExcelScript.Workbook) { const sheet = workbook.getActiveWorksheet(); // Add sample data (state names and values). const data = [ ["State", "Sales"], ["California", 450000], ["Texas", 380000], ["Florida", 320000], ["New York", 410000], ["Illinois", 280000], ["Pennsylvania", 240000], ["Ohio", 220000], ["Georgia", 195000], ["North Carolina", 185000], ["Michigan", 175000] ]; const dataRange = sheet.getRange("A1:B11"); dataRange.setValues(data); // Create region map chart. const chart = sheet.addChart( ExcelScript.ChartType.regionMap, dataRange ); chart.setPosition("D1"); chart.getTitle().setText("Sales by State"); chart.getLegend().setPosition(ExcelScript.ChartLegendPosition.right); } ``` -------------------------------- ### Create a Scatter with Smooth Lines Chart Source: https://github.com/officedev/office-scripts-docs/blob/main/docs/resources/samples/chart-samples.md Generates a scatter chart with smooth, curved connecting lines. This example uses sample data for two series and positions the legend at the bottom. ```TypeScript function main(workbook: ExcelScript.Workbook) { const sheet = workbook.getActiveWorksheet(); // Add sample data. const data = [ ["X", "Series 1", "Series 2"], [1, 10, 15], [2, 15, 18], [3, 25, 22], [4, 40, 28], [5, 60, 35], [6, 85, 43], [7, 115, 52] ]; const dataRange = sheet.getRange("A1:C8"); dataRange.setValues(data); // Create scatter chart with smooth lines. const chart = sheet.addChart( ExcelScript.ChartType.xyscatterSmooth, dataRange ); chart.setPosition("D1"); chart.getTitle().setText("Growth Comparison"); chart.getLegend().setPosition(ExcelScript.ChartLegendPosition.bottom); } ``` -------------------------------- ### Create Teams meeting for interviews Source: https://github.com/officedev/office-scripts-docs/blob/main/docs/resources/scenarios/schedule-interviews-in-teams.md Utilize the Microsoft Teams connector to create a meeting. This action is typically placed within a 'For each' loop generated by dynamic content from the 'Run script' action. Configure subject, message, time zone, start and end times, calendar ID, and attendees. ```Power Automate Action: Create a Teams meeting Connector: Microsoft Teams Subject: Contoso Interview Message: *Message* (dynamic content from Run script) Time zone: Pacific Standard Time Start time: *StartTime* (dynamic content from Run script) End time: *FinishTime* (dynamic content from Run script) Calendar id: Calendar Required attendees: *CandidateEmail* ; *InterviewerEmail* (dynamic content from Run script) ``` -------------------------------- ### Run Script to Read Data Source: https://github.com/officedev/office-scripts-docs/blob/main/docs/resources/samples/write-large-dataset.md Use the 'Run script' action from the Excel Online (Business) connector to read a batch of data. Specify the file, script name, start row, and batch size. ```Power Automate Excel Online (Business) - Run script Location: OneDrive for Business Document Library: OneDrive File: "SampleData.xlsx" Script: Read selected rows startRow: currentRow (dynamic content) batchSize: batchSize (dynamic content) ``` -------------------------------- ### Get table data from worksheet Source: https://github.com/officedev/office-scripts-docs/blob/main/docs/tutorials/excel-power-automate-returns.md This code retrieves data from a table within the 'H1' worksheet. It assumes the table is the first one on the sheet and gets the values from the range between the header and total rows. ```TypeScript // Get the H1 worksheet. let worksheet = workbook.getWorksheet("H1"); // Get the first (and only) table in the worksheet. let table = worksheet.getTables()[0]; // Get the data from the table. let tableValues = table.getRangeBetweenHeaderAndTotal().getValues(); ``` -------------------------------- ### Define main function with parameters Source: https://github.com/officedev/office-scripts-docs/blob/main/docs/tutorials/excel-power-automate-trigger.md This is the entry point for the script. It accepts workbook object and email details as parameters. ```TypeScript function main( workbook: ExcelScript.Workbook, from: string, dateReceived: string, subject: string) { } ``` -------------------------------- ### Set up workbook with worksheet, table, and PivotTable Source: https://github.com/officedev/office-scripts-docs/blob/main/docs/tutorials/excel-power-automate-trigger.md Use this script to prepare your Excel workbook by creating a dedicated worksheet for email data, a table to store it, and a PivotTable to summarize subjects. Ensure consistent naming for Power Automate integration. ```typescript function main(workbook: ExcelScript.Workbook) { // Add a new worksheet to store the email table. let emailsSheet = workbook.addWorksheet("Emails"); // Add data and create a table emailsSheet.getRange("A1:D1").setValues([ ["Date", "Day of the week", "Email address", "Subject"] ]); let newTable = workbook.addTable(emailsSheet.getRange("A1:D2"), true); newTable.setName("EmailTable"); // Add a new PivotTable to a new worksheet let pivotWorksheet = workbook.addWorksheet("Subjects"); let newPivotTable = workbook.addPivotTable("Pivot", "EmailTable", pivotWorksheet.getRange("A3:C20")); // Setup the pivot hierarchies newPivotTable.addRowHierarchy(newPivotTable.getHierarchy("Day of the week")); newPivotTable.addRowHierarchy(newPivotTable.getHierarchy("Email address")); newPivotTable.addDataHierarchy(newPivotTable.getHierarchy("Subject")); } ``` -------------------------------- ### Apply Color Scale Conditional Formatting - Office Scripts Source: https://github.com/officedev/office-scripts-docs/blob/main/docs/resources/samples/conditional-formatting-samples.md Applies a three-color scale (red, white, blue) to a selected range. The minimum value gets blue, the maximum gets red, and a midpoint is set at the 50th percentile with an off-white color. Ensure the 'ColorScale' worksheet exists and the range 'B2:M13' is valid. ```typescript function main(workbook: ExcelScript.Workbook) { // Get the range to format. const sheet = workbook.getWorksheet("ColorScale"); const dataRange = sheet.getRange("B2:M13"); sheet.activate(); // Create a new conditional formatting object by adding one to the range. const conditionalFormatting = dataRange.addConditionalFormat(ExcelScript.ConditionalFormatType.colorScale); // Set the colors for the three parts of the scale: minimum, midpoint, and maximum. conditionalFormatting.getColorScale().setCriteria({ minimum: { color: "#5A8AC6", /* A pale blue. */ type: ExcelScript.ConditionalFormatColorCriterionType.lowestValue }, midpoint: { color: "#FCFCFF", /* Slightly off-white. */ formula: '=50', type: ExcelScript.ConditionalFormatColorCriterionType.percentile }, maximum: { color: "#F8696B", /* A pale red. */ type: ExcelScript.ConditionalFormatColorCriterionType.highestValue } }); } ``` -------------------------------- ### Script with a default parameter Source: https://github.com/officedev/office-scripts-docs/blob/main/docs/develop/power-automate-parameters-returns.md Define a parameter in the `main` function to accept input from Power Automate. Default values can be provided. ```typescript function main(workbook: ExcelScript.Workbook, location: string = "Seattle") { // ... script logic here } ``` -------------------------------- ### Highlight Blank Cells Source: https://github.com/officedev/office-scripts-docs/blob/main/docs/resources/samples/range-samples.md Gets all the blank cells in the current worksheet's used range and highlights them with a yellow background. ```TypeScript function main(workbook: ExcelScript.Workbook) { // Get the current used range. let range = workbook.getActiveWorksheet().getUsedRange(); // Get all the blank cells. let blankCells = range.getSpecialCells(ExcelScript.SpecialCellType.blanks); // Highlight the blank cells with a yellow background. blankCells.getFormat().getFill().setColor("yellow"); } ``` -------------------------------- ### Parse date and get day of the week Source: https://github.com/officedev/office-scripts-docs/blob/main/docs/tutorials/excel-power-automate-trigger.md Converts the input date string into a Date object and extracts the full name of the day of the week. ```TypeScript // Parse the received date string to determine the day of the week. let emailDate = new Date(dateReceived); let dayName = emailDate.toLocaleDateString("en-US", { weekday: 'long' }); ``` -------------------------------- ### Change Adjacent Cells Source: https://github.com/officedev/office-scripts-docs/blob/main/docs/resources/samples/range-samples.md Gets adjacent cells using relative references. Fails if the active cell is in the top row when referencing the cell above. ```TypeScript function main(workbook: ExcelScript.Workbook) { // Get the currently active cell in the workbook. let activeCell = workbook.getActiveCell(); console.log(`The active cell's address is: ${activeCell.getAddress()}`); // Get the cell to the right of the active cell and set its value and color. let rightCell = activeCell.getOffsetRange(0,1); rightCell.setValue("Right cell"); console.log(`The right cell's address is: ${rightCell.getAddress()}`); rightCell.getFormat().getFont().setColor("Magenta"); rightCell.getFormat().getFill().setColor("Cyan"); // Get the cell to the above of the active cell and set its value and color. // Note that this operation will fail if the active cell is in the top row. let aboveCell = activeCell.getOffsetRange(-1, 0); aboveCell.setValue("Above cell"); console.log(`The above cell's address is: ${aboveCell.getAddress()}`); aboveCell.getFormat().getFont().setColor("White"); aboveCell.getFormat().getFill().setColor("Black"); } ``` -------------------------------- ### Accept workbook imports as parameters Source: https://github.com/officedev/office-scripts-docs/blob/main/docs/develop/user-input.md This script demonstrates how to accept workbook imports for parameters, allowing users to import data directly into the script. Both `productData` and `salesData` are defined as two-dimensional string arrays to accept workbook imports. ```TypeScript /**​ * This script generates a monthly sales report.​ * @param productData The product data for this month.​ * @param salesData The sales data for this month.​ */ function main(workbook: ExcelScript.Workbook, productData: string[][], salesData: string[][]) { // Code to process data goes here. // Both the `productData` and `salesData` parameters accept workbook imports. }​ ``` -------------------------------- ### Initialize currentRow Variable Source: https://github.com/officedev/office-scripts-docs/blob/main/docs/resources/samples/write-large-dataset.md Initialize an integer variable to track the current row being processed. This is the starting point for reading and writing data. ```Power Automate Initialize variable Name: currentRow Type: Integer Value: 0 ``` -------------------------------- ### Checkout a branch Source: https://github.com/officedev/office-scripts-docs/blob/main/Contributing.md Switch to a specific branch to update your local files to the current state of that branch. This command updates the files in your local repository. ```bash git checkout X2 ``` -------------------------------- ### Sample JSON output from Excel table Source: https://github.com/officedev/office-scripts-docs/blob/main/docs/resources/samples/get-table-data.md This is an example of the JSON output generated from the "PlainTable" worksheet, representing each row as a JSON object. ```json [{ "Event ID": "E107", "Date": "2020-12-10", "Location": "Montgomery", "Capacity": "10", "Speakers": "Debra Berger" }, { "Event ID": "E108", "Date": "2020-12-11", "Location": "Montgomery", "Capacity": "10", "Speakers": "Delia Dennis" }, { "Event ID": "E109", "Date": "2020-12-12", "Location": "Montgomery", "Capacity": "10", "Speakers": "Diego Siciliani" }, { "Event ID": "E110", "Date": "2020-12-13", "Location": "Boise", "Capacity": "25", "Speakers": "Gerhart Moller" }, { "Event ID": "E111", "Date": "2020-12-14", "Location": "Salt Lake City", "Capacity": "20", "Speakers": "Grady Archie" }, { "Event ID": "E112", "Date": "2020-12-15", "Location": "Fremont", "Capacity": "25", "Speakers": "Irvin Sayers" }, { "Event ID": "E113", "Date": "2020-12-16", "Location": "Salt Lake City", "Capacity": "20", "Speakers": "Isaiah Langer" }, { "Event ID": "E114", "Date": "2020-12-17", "Location": "Salt Lake City", "Capacity": "20", "Speakers": "Johanna Lorenz" }] ``` -------------------------------- ### Clone Office Scripts Docs Repository Source: https://github.com/officedev/office-scripts-docs/blob/main/Contributing.md Clone the office-scripts-docs repository to your local machine using Git. This command sets up your local copy for development. ```bash git clone https://github.com//office-scripts-docs.git ``` -------------------------------- ### Create Bubble Chart in Excel Source: https://github.com/officedev/office-scripts-docs/blob/main/docs/resources/samples/chart-samples.md This script adds sample data and creates a bubble chart to visualize product analysis based on price, quality, and market share. Each product is added as a separate data series. ```TypeScript function main(workbook: ExcelScript.Workbook) { const sheet = workbook.getActiveWorksheet(); // Add sample data for bubble chart. // Each product is a separate data series with X, Y, and Size values. const data = [ ["Product", "Price ($", "Quality Score", "Market Share"], ["Laptops", 150, 85, 25], ["Tablets", 200, 90, 40], ["Phones", 100, 75, 15], ["Monitors", 250, 92, 35], ["Keyboards", 175, 88, 30], ["Mice", 120, 80, 20] ]; const dataRange = sheet.getRange("A1:D7"); dataRange.setValues(data); // Create bubble chart - manually add each series. const chart = sheet.addChart( ExcelScript.ChartType.bubble, sheet.getRange("B1:D1") // Start with just headers to create empty chart. ); chart.setPosition("A9"); chart.getTitle().setText("Product Analysis: Price vs Quality (Market Share)"); // Remove any default series that were created. while (chart.getSeries().length > 0) { chart.getSeries()[0].delete(); } // Add each product as its own series. for (let i = 2; i <= 7; i++) { const productName = sheet.getRange(`A${ i } `).getValue() as string; const newSeries = chart.addChartSeries(); newSeries.setName(productName); newSeries.setXAxisValues(sheet.getRange(`B${ i }:B${ i } `)); newSeries.setValues(sheet.getRange(`C${ i }:C${ i } `)); newSeries.setBubbleSizes(sheet.getRange(`D${ i }:D${ i } `)); } chart.getLegend().setPosition(ExcelScript.ChartLegendPosition.right); } ``` -------------------------------- ### Set fill color for a range in Excel Source: https://github.com/officedev/office-scripts-docs/blob/main/docs/tutorials/excel-tutorial.md This code gets the current worksheet and sets the fill color for a specified range. Use this to apply background colors to cells. ```TypeScript function main(workbook: ExcelScript.Workbook) { // Set fill color to FFC000 for range Sheet1!A2:C2 let selectedSheet = workbook.getActiveWorksheet(); selectedSheet.getRange("A2:C2").getFormat().getFill().setColor("FFC000"); } ``` ```TypeScript selectedSheet.getRange("A3:C3").getFormat().getFill().setColor("yellow"); ``` -------------------------------- ### Stage and commit changes Source: https://github.com/officedev/office-scripts-docs/blob/main/Contributing.md Stage all modified and new files recursively and commit them to your local repository with a descriptive message. The -v and -a switches are optional. ```bash git add . git commit -v -a -m "" ``` -------------------------------- ### Write Current Date and Time to Cells Source: https://github.com/officedev/office-scripts-docs/blob/main/docs/resources/samples/javascript-dates.md Gets the current date and time using the JavaScript Date object and writes them to cells A1 and B1 of the active worksheet. ```TypeScript function main(workbook: ExcelScript.Workbook) { // Get the cells at A1 and B1. let dateRange = workbook.getActiveWorksheet().getRange("A1"); let timeRange = workbook.getActiveWorksheet().getRange("B1"); // Get the current date and time with the JavaScript Date object. let date = new Date(Date.now()); // Add the date string to A1. dateRange.setValue(date.toLocaleDateString()); // Add the time string to B1. timeRange.setValue(date.toLocaleTimeString()); } ``` -------------------------------- ### Show Values as Percentage of Grand Total Source: https://github.com/officedev/office-scripts-docs/blob/main/docs/develop/pivottables.md Use `ExcelScript.ShowAsCalculation.percentOfGrandTotal` to display values as a percentage of the grand total for the field. This requires no additional setup beyond defining the rule. ```typescript const farmSales = farmPivot.getDataHierarchy("Sum of Crates Sold at Farm"); const rule : ExcelScript.ShowAsRule = { calculation: ExcelScript.ShowAsCalculation.percentOfGrandTotal }; farmSales.setShowAs(rule); ``` -------------------------------- ### Create a Scatter Chart Source: https://github.com/officedev/office-scripts-docs/blob/main/docs/resources/samples/chart-samples.md Use this snippet to create a basic scatter chart. It requires sample data and sets the chart title and axis properties. ```TypeScript function main(workbook: ExcelScript.Workbook) { const sheet = workbook.getActiveWorksheet(); // Add sample data. const data = [ ["Study Hours", "Test Score"], [2, 65], [3, 68], [4, 72], [5, 75], [5.5, 78], [6, 82], [7, 85], [7.5, 88], [8, 90], [9, 92], [10, 95] ]; const dataRange = sheet.getRange("A1:B12"); dataRange.setValues(data); // Create scatter chart. const chart = sheet.addChart( ExcelScript.ChartType.xyscatter, dataRange ); chart.setPosition("D1"); chart.getTitle().setText("Study Hours vs Test Scores"); // Customize scatter chart. chart.getAxes().getCategoryAxis().setDisplayUnit(ExcelScript.ChartAxisDisplayUnit.none); chart.getAxes().getValueAxis().setMinimum(0); chart.getAxes().getValueAxis().setMaximum(100); // Remove legend as there's only one series. chart.getLegend().setVisible(false); } ``` -------------------------------- ### Check for Blank First Cell with Semicolon Separator Source: https://github.com/officedev/office-scripts-docs/blob/main/docs/resources/samples/convert-csv.md Adjust the condition to check if the first cell in a row starts with a semicolon, which is necessary when processing CSV files that use semicolons as delimiters. ```TypeScript if (row[0].charAt(0) === ';') { ``` -------------------------------- ### Create 100% Stacked Cone Column Chart Source: https://github.com/officedev/office-scripts-docs/blob/main/docs/resources/samples/chart-samples.md Adds sample data and generates a 100% stacked 3D cone column chart showing quarterly performance as percentages. Sets the chart title and legend position. ```TypeScript function main(workbook: ExcelScript.Workbook) { const sheet = workbook.getActiveWorksheet(); // Add sample data. const data = [ ["Quarter", "Target", "Achieved"], ["Q1", 100000, 95000], ["Q2", 120000, 125000], ["Q3", 130000, 128000], ["Q4", 150000, 158000] ]; const dataRange = sheet.getRange("A1:C5"); dataRange.setValues(data); // Create 100% stacked cone column chart. const chart = sheet.addChart( ExcelScript.ChartType.coneColStacked100, dataRange ); chart.setPosition("D1"); chart.getTitle().setText("Quarterly Performance (100% Stacked 3D Cone)"); chart.getLegend().setPosition(ExcelScript.ChartLegendPosition.bottom); } ``` -------------------------------- ### Create Line Chart with Markers Source: https://github.com/officedev/office-scripts-docs/blob/main/docs/resources/samples/chart-samples.md Use this to create a line chart with markers to emphasize individual data points. Ensure data is present in the specified range before execution. ```TypeScript function main(workbook: ExcelScript.Workbook) { const sheet = workbook.getActiveWorksheet(); // Add sample data. const data = [ ["Week", "Website A", "Website B", "Website C"], ["Week 1", 1250, 980, 1100], ["Week 2", 1380, 1050, 1150], ["Week 3", 1520, 1180, 1320], ["Week 4", 1690, 1280, 1450], ["Week 5", 1850, 1420, 1580], ["Week 6", 2020, 1590, 1720] ]; const dataRange = sheet.getRange("A1:D7"); dataRange.setValues(data); // Create line chart with markers. const chart = sheet.addChart( ExcelScript.ChartType.lineMarkers, dataRange ); chart.setPosition("A9"); chart.getTitle().setText("Weekly Visitor Growth"); // Customize markers. const series = chart.getSeries(); series.forEach((s) => { s.setMarkerSize(8); s.setMarkerStyle(ExcelScript.ChartMarkerStyle.circle); }); } ``` -------------------------------- ### Get Event Data from Excel Source: https://github.com/officedev/office-scripts-docs/blob/main/docs/resources/samples/excel-cross-reference.md This script retrieves event data from the first table in the 'Keys' worksheet. It formats the data as an array of EventData objects and returns it as a JSON string for use in Power Automate. ```TypeScript function main(workbook: ExcelScript.Workbook): string { // Get the first table in the "Keys" worksheet. let table = workbook.getWorksheet('Keys').getTables()[0]; // Get the rows in the event table. let range = table.getRangeBetweenHeaderAndTotal(); let rows = range.getValues(); // Save each row as an EventData object. This lets them be passed through Power Automate. let records: EventData[] = []; for (let row of rows) { let [eventId, date, location, capacity] = row; records.push({ eventId: eventId as string, date: date as number, location: location as string, capacity: capacity as number }) } // Log the event data to the console and return it for a flow. let stringResult = JSON.stringify(records); console.log(stringResult); return stringResult; } // An interface representing a row of event data. interface EventData { eventId: string date: number location: string capacity: number } ``` -------------------------------- ### Create and push a new branch Source: https://github.com/officedev/office-scripts-docs/blob/main/Contributing.md Use these Git Bash commands to create a new local branch from the main branch and push it to your GitHub fork. ```bash git pull upstream main: ``` ```bash git push origin ``` ```bash git checkout ``` -------------------------------- ### Add data to a range in Office Scripts Source: https://github.com/officedev/office-scripts-docs/blob/main/docs/resources/samples/range-samples.md Adds predefined data to a new worksheet, starting in cell A1. The data can be sourced from various places. This script creates a new worksheet named 'DataSheet'. ```TypeScript function main(workbook: ExcelScript.Workbook) { // The getData call could be replaced by input from Power Automate or a fetch call. const data = getData(); // Create a new worksheet and switch to it. const newWorksheet = workbook.addWorksheet("DataSheet"); newWorksheet.activate(); // Get a range matching the size of the data. const dataRange = newWorksheet.getRangeByIndexes( 0, 0, data.length, data[0].length); // Set the data as the values in the range. dataRange.setValues(data); } function getData(): string[][] { return [["Abbreviation", "State/Province", "Country"], ["AL", "Alabama", "USA"], ["AK", "Alaska", "USA"], ["AZ", "Arizona", "USA"], ["AR", "Arkansas", "USA"], ["CA", "California", "USA"], ["CO", "Colorado", "USA"], ["CT", "Connecticut", "USA"], ["DE", "Delaware", "USA"], ["DC", "District of Columbia", "USA"], ["FL", "Florida", "USA"], ["GA", "Georgia", "USA"], ["HI", "Hawaii", "USA"], ["ID", "Idaho", "USA"], ["IL", "Illinois", "USA"], ["IN", "Indiana", "USA"], ["IA", "Iowa", "USA"], ["KS", "Kansas", "USA"], ["KY", "Kentucky", "USA"], ["LA", "Louisiana", "USA"], ["ME", "Maine", "USA"], ["MD", "Maryland", "USA"], ["MA", "Massachusetts", "USA"], ["MI", "Michigan", "USA"], ["MN", "Minnesota", "USA"], ["MS", "Mississippi", "USA"], ["MO", "Missouri", "USA"], ["MT", "Montana", "USA"], ["NE", "Nebraska", "USA"], ["NV", "Nevada", "USA"], ["NH", "New Hampshire", "USA"], ["NJ", "New Jersey", "USA"], ["NM", "New Mexico", "USA"], ["NY", "New York", "USA"], ["NC", "North Carolina", "USA"], ["ND", "North Dakota", "USA"], ["OH", "Ohio", "USA"], ["OK", "Oklahoma", "USA"], ["OR", "Oregon", "USA"], ["PA", "Pennsylvania", "USA"], ["RI", "Rhode Island", "USA"], ["SC", "South Carolina", "USA"], ["SD", "South Dakota", "USA"], ["TN", "Tennessee", "USA"], ["TX", "Texas", "USA"], ["UT", "Utah", "USA"], ["VT", "Vermont", "USA"], ["VA", "Virginia", "USA"], ["WA", "Washington", "USA"], ["WV", "West Virginia", "USA"], ["WI", "Wisconsin", "USA"], ["WY", "Wyoming", "USA"], ["AB", "Alberta", "CAN"], ["BC", "British Columbia", "CAN"], ["MB", "Manitoba", "CAN"], ["NB", "New Brunswick", "CAN"], ["NL", "Newfoundland and Labrador", "CAN"], ["NT", "Northwest Territory", "CAN"], ["NS", "Nova Scotia", "CAN"], ["NU", "Nunavut Territory", "CAN"], ["ON", "Ontario", "CAN"], ["PE", "Prince Edward Island", "CAN"], ["QC", "Quebec", "CAN"], ["SK", "Saskatchewan", "CAN"], ["YT", "Yukon Territory", "CAN"]]; } ``` -------------------------------- ### Create Pie Chart Source: https://github.com/officedev/office-scripts-docs/blob/main/docs/resources/samples/chart-samples.md This script generates a pie chart to visualize market share distribution. It includes sample data, sets the chart type, position, title, and customizes the legend and data labels to show percentages. ```TypeScript function main(workbook: ExcelScript.Workbook) { const sheet = workbook.getActiveWorksheet(); // Add sample data with multiple slices. const data = [ ["Company", "Market Share"], ["Alpha Corp", 28.5], ["Beta Inc", 22.3], ["Gamma LLC", 18.7], ["Delta Co", 15.2], ["Others", 15.3] ]; const dataRange = sheet.getRange("A1:B6"); dataRange.setValues(data); // Create pie chart. const chart = sheet.addChart( ExcelScript.ChartType.pie, dataRange ); chart.setPosition("D1"); chart.getTitle().setText("Market Share Distribution"); // Customize pie chart. chart.getLegend().setPosition(ExcelScript.ChartLegendPosition.right); // Add data labels showing percentages. const series = chart.getSeries()[0]; series.setHasDataLabels(true); series.getDataLabels().setShowPercentage(true); series.getDataLabels().setShowSeriesName(false); series.getDataLabels().setShowCategoryName(false); series.getDataLabels().setShowValue(false); } ``` -------------------------------- ### Create Stock VOHLC Chart in Excel Source: https://github.com/officedev/office-scripts-docs/blob/main/docs/resources/samples/chart-samples.md This script creates a Volume-Open-High-Low-Close stock chart, providing a complete stock analysis view. It requires data including Date, Volume, Open, High, Low, and Close. The chart is positioned, titled, and the value axis limits are set. Volume bars are styled for better visibility. ```TypeScript function main(workbook: ExcelScript.Workbook) { const sheet = workbook.getActiveWorksheet(); // Add sample data (Date, Volume, Open, High, Low, Close). const data = [ ["Date", "Volume", "Open", "High", "Low", "Close"], ["1/1/2024", 2500000, 150.00, 152.50, 148.20, 151.00], ["1/2/2024", 3200000, 151.00, 153.80, 150.50, 152.30], ["1/3/2024", 2800000, 152.30, 154.20, 151.80, 153.50], ["1/4/2024", 3500000, 153.50, 155.00, 152.30, 153.80], ["1/5/2024", 4100000, 153.80, 156.50, 153.50, 155.20] ]; const dataRange = sheet.getRange("A1:F6"); dataRange.setValues(data); // Create VOHLC stock chart. const chart = sheet.addChart( ExcelScript.ChartType.stockVOHLC, dataRange ); chart.setPosition("A8"); chart.getTitle().setText("Complete Stock Analysis (VOHLC)"); // Customize to improve visibility of stock lines against volume bars. chart.getAxes().getValueAxis().setMinimum(145); chart.getAxes().getValueAxis().setMaximum(160); // Make the volume bars more transparent or lighter colored. const volumeSeries = chart.getSeries()[0]; volumeSeries.getFormat().getFill().setSolidColor("#B0C4DE"); // Light steel blue. } ``` -------------------------------- ### Marking a main function as async in Office Scripts Source: https://github.com/officedev/office-scripts-docs/blob/main/docs/develop/external-calls.md When making external API calls, your script's main function must be marked as `async` and return a `Promise`. This example shows the basic signature. ```typescript async function main(workbook: ExcelScript.Workbook) : Promise ``` -------------------------------- ### Create Pie of Pie Chart Source: https://github.com/officedev/office-scripts-docs/blob/main/docs/resources/samples/chart-samples.md Adds sample data and creates a pie of pie chart to visualize market segment analysis. Sets the chart title and legend position. ```TypeScript function main(workbook: ExcelScript.Workbook) { const sheet = workbook.getActiveWorksheet(); // Add sample data. const data = [ ["Segment", "Value"], ["Enterprise", 425000], ["Small Business", 285000], ["Consumer", 190000], ["Education", 65000], ["Government", 55000], ["Non-Profit", 30000] ]; const dataRange = sheet.getRange("A1:B7"); dataRange.setValues(data); // Create pie of pie chart. const chart = sheet.addChart( ExcelScript.ChartType.pieOfPie, dataRange ); chart.setPosition("D1"); chart.getTitle().setText("Market Segment Analysis (Pie of Pie)"); chart.getLegend().setPosition(ExcelScript.ChartLegendPosition.right); } ``` -------------------------------- ### Read selected rows from Excel Source: https://github.com/officedev/office-scripts-docs/blob/main/docs/resources/samples/write-large-dataset.md Use this script to read a specified number of rows from the first worksheet, starting from a given row. It's useful for batch processing data when the entire dataset is too large to handle at once. ```TypeScript function main( workbook: ExcelScript.Workbook, startRow: number, batchSize: number ): string[][] { // This script only reads the first worksheet in the workbook. const sheet = workbook.getWorksheets()[0]; // Get the boundaries of the range. // Note that we're assuming usedRange is too big to read or write as a single range. const usedRange = sheet.getUsedRange(); const lastColumnIndex = usedRange.getLastColumn().getColumnIndex(); const lastRowindex = usedRange.getLastRow().getRowIndex(); // If we're starting past the last row, exit the script. if (startRow > lastRowindex) { return [[]]; } // Get the next batch or the rest of the rows, whichever is smaller. const rowCountToRead = Math.min(batchSize, (lastRowindex - startRow + 1)); const rangeToRead = sheet.getRangeByIndexes(startRow, 0, rowCountToRead, lastColumnIndex + 1); return rangeToRead.getValues() as string[][]; } ``` -------------------------------- ### Record sent invites using Excel script Source: https://github.com/officedev/office-scripts-docs/blob/main/docs/resources/scenarios/schedule-interviews-in-teams.md After creating a Teams meeting, use another 'Run script' action to record the sent invites back into the Excel workbook. Ensure to switch the input for the 'invites' parameter to 'entire array' to pass all relevant data. ```Power Automate Action: Run script Connector: Excel Online (Business) Location: OneDrive for Business Document Library: OneDrive File: hr-interviews.xlsx Script: Record Sent Invites invites: *result* (dynamic content from Run script - ensure 'Switch input to entire array' is selected) ``` -------------------------------- ### Create a new branch from upstream main Source: https://github.com/officedev/office-scripts-docs/blob/main/Contributing.md After a merge, create a new local branch from the latest OfficeDev/office-scripts-docs main branch to avoid merge conflicts in future pull requests. This example creates branch 'X2'. ```bash cd office-scripts-docs git pull upstream main:X2 git push origin X2 ``` -------------------------------- ### Create 100% Stacked Line Chart with Markers Source: https://github.com/officedev/office-scripts-docs/blob/main/docs/resources/samples/chart-samples.md Use this script to create a 100% stacked line chart with markers. It adds sample data and configures the chart type, position, title, and legend. ```TypeScript function main(workbook: ExcelScript.Workbook) { const sheet = workbook.getActiveWorksheet(); // Add sample data. const data = [ ["Quarter", "Product Line A", "Product Line B", "Product Line C"], ["Q1", 35, 40, 25], ["Q2", 38, 37, 25], ["Q3", 40, 35, 25], ["Q4", 42, 33, 25] ]; const dataRange = sheet.getRange("A1:D5"); dataRange.setValues(data); // Create 100% stacked line chart with markers. const chart = sheet.addChart( ExcelScript.ChartType.lineMarkersStacked100, dataRange ); chart.setPosition("A7"); chart.getTitle().setText("Product Line Market Share Trends"); chart.getLegend().setPosition(ExcelScript.ChartLegendPosition.bottom); } ```