创建锦标赛
使用集合让一切井井有条
根据您的偏好保存内容并对其进行分类。
编码水平:初级
时长:5 分钟
项目类型:使用自定义菜单实现自动化
目标
- 了解解决方案的功能。
- 了解 Apps 脚本服务在解决方案中的作用。
- 设置脚本。
- 运行脚本。
关于此解决方案
创建最多可容纳 64 人或团队的锦标赛对阵表。此解决方案会创建一个树状图,用于表示单淘汰赛。

运作方式
该脚本会遍历玩家列表,并确定赛程中需要多少轮。该脚本会设置对阵表工作表的格式,以创建树状图,并将参赛者的姓名添加到第一轮。
Apps 脚本服务
此解决方案使用以下服务:
电子表格服务 - 获取选手范围并创建比赛树状图。
前提条件
如需使用此示例,您需要满足以下前提条件:
- Google 账号(Google Workspace 账号可能需要管理员批准)。
- 可访问互联网的网络浏览器。
设置脚本
点击以下按钮,复制创建锦标赛对阵表示例电子表格。
制作副本
运行脚本
- 在复制的电子表格中,依次点击对阵表生成器 > 创建对阵表。您可能需要刷新页面才能看到此自定义菜单。
根据提示为脚本授权。
如果 OAuth 权限请求页面显示警告此应用未经过验证,请继续操作,依次选择高级 >
前往“{项目名称}”(不安全)。
依次点击对阵表制作工具
> 再次点击创建对阵表。
切换到赛程标签页,查看赛事赛程。
查看代码
如需查看此解决方案的 Apps 脚本代码,请点击下方的查看源代码:
贡献者
此示例由 Google 在 Google 开发者专家的帮助下维护。
后续步骤
如未另行说明,那么本页面中的内容已根据知识共享署名 4.0 许可获得了许可,并且代码示例已根据 Apache 2.0 许可获得了许可。有关详情,请参阅 Google 开发者网站政策。Java 是 Oracle 和/或其关联公司的注册商标。
最后更新时间 (UTC):2025-08-31。
[null,null,["最后更新时间 (UTC):2025-08-31。"],[[["\u003cp\u003eThis script automates the creation of a single-elimination tournament bracket for up to 64 players or teams in Google Sheets.\u003c/p\u003e\n"],["\u003cp\u003eIt uses the Spreadsheet service to get player data and generate the bracket diagram on a separate sheet.\u003c/p\u003e\n"],["\u003cp\u003eUsers need a Google Account and web browser to utilize this tool, and can set it up by making a copy of the provided spreadsheet and running the script from the custom menu.\u003c/p\u003e\n"],["\u003cp\u003eThe script randomly assigns players to the bracket, ensuring each spot is filled, and accommodates byes for an uneven number of participants.\u003c/p\u003e\n"]]],["This script automates the creation of a single-elimination tournament bracket for up to 64 players. Utilizing the Spreadsheet service, it determines the necessary rounds, formats the \"Bracket\" sheet to display a tree diagram, and populates the first round with player names from the \"Players\" sheet. A custom menu, \"Bracket maker\", allows the user to trigger the `createBracket` function, which generates the bracket after obtaining user authorization. The code then uses loops to manage player distribution and bracket formatting.\n"],null,["# Create a tournament bracket\n\n**Coding level** : Beginner \n\n**Duration** : 5 minutes \n\n**Project type** : Automation with a [custom menu](/apps-script/guides/menus)\n\nObjectives\n----------\n\n- Understand what the solution does.\n- Understand what the Apps Script services do within the solution.\n- Set up the script.\n- Run the script.\n\nAbout this solution\n-------------------\n\nCreate a tournament bracket for up to 64 people or teams. This solution creates\na tree diagram that represents a single-elimination tournament.\n\n### How it works\n\nThe script loops through the list of players and determines how many rounds are\nneeded in the bracket. The script formats the **Bracket** sheet to create the\ntree diagram and adds the players' names to the first round.\n\n### Apps Script services\n\nThis solution uses the following service:\n\n[Spreadsheet service](/apps-script/reference/spreadsheet)--Gets the range of\nplayers and creates the tree diagram for the tournament.\n\nPrerequisites\n-------------\n\nTo use this sample, you need the following prerequisites:\n\n- A Google Account (Google Workspace accounts might require administrator approval).\n- A web browser with access to the internet.\n\nSet up the script\n-----------------\n\nClick the following button to make a copy of the **Create a tournament bracket**\nsample spreadsheet.\n\n[Make a copy](https://docs.google.com/spreadsheets/d/19AUMQVmtGmNgX1jhs5dBQ4D_Afb3DMa3MNHB4PHD3aI/copy)\n\nRun the script\n--------------\n\n1. In your copied spreadsheet, click **Bracket maker** \\\u003e **Create\n bracket**. You might need to refresh the page for this custom menu to appear.\n2. When prompted, authorize the script.\n If the OAuth consent screen displays the warning, **This app isn't verified** ,\n continue by selecting **Advanced** \\\u003e\n **Go to {Project Name} (unsafe)**.\n\n3. Click **Bracket maker**\n \\\u003e **Create bracket** again.\n\n4. Switch to the **Bracket** tab to view the tournament bracket.\n\nReview the code\n---------------\n\nTo review the Apps Script code for this solution, click\n**View source code** below: \n\n#### View source code\n\n### Code.gs\n\n\u003cbr /\u003e\n\nsolutions/automations/bracket-maker/Code.js \n[View on GitHub](https://github.com/googleworkspace/apps-script-samples/blob/main/solutions/automations/bracket-maker/Code.js) \n\n```javascript\n// To learn how to use this script, refer to the documentation:\n// https://developers.google.com/apps-script/samples/automations/bracket-maker\n\n/*\nCopyright 2022 Google LLC\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n https://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nconst RANGE_PLAYER1 = 'FirstPlayer';\nconst SHEET_PLAYERS = 'Players';\nconst SHEET_BRACKET = 'Bracket';\nconst CONNECTOR_WIDTH = 15;\n\n/**\n * Adds a custom menu item to run the script.\n */\nfunction onOpen() {\n let ss = SpreadsheetApp.getActiveSpreadsheet();\n ss.addMenu('Bracket maker',\n [{name: 'Create bracket', functionName: 'createBracket'}]);\n}\n\n/**\n * Creates the brackets based on the data provided on the players.\n */\nfunction createBracket() {\n let ss = SpreadsheetApp.getActiveSpreadsheet();\n let rangePlayers = ss.getRangeByName(RANGE_PLAYER1);\n let sheetControl = ss.getSheetByName(SHEET_PLAYERS);\n let sheetResults = ss.getSheetByName(SHEET_BRACKET);\n\n // Gets the players from column A. Assumes the entire column is filled.\n rangePlayers = rangePlayers.offset(0, 0, sheetControl.getMaxRows() -\n rangePlayers.getRowIndex() + 1, 1);\n let players = rangePlayers.getValues();\n\n // Figures out how many players there are by skipping the empty cells.\n let numPlayers = 0;\n for (let i = 0; i \u003c players.length; i++) {\n if (!players[i][0] || players[i][0].length == 0) {\n break;\n }\n numPlayers++;\n }\n players = players.slice(0, numPlayers);\n\n // Provides some error checking in case there are too many or too few players/teams.\n if (numPlayers \u003e 64) {\n Browser.msgBox('Sorry, this script can only create brackets for 64 or fewer players.');\n return; // Early exit\n }\n\n if (numPlayers \u003c 3) {\n Browser.msgBox('Sorry, you must have at least 3 players.');\n return; // Early exit\n }\n\n // Clears the 'Bracket' sheet and all formatting.\n sheetResults.clear();\n\n let upperPower = Math.ceil(Math.log(numPlayers) / Math.log(2));\n\n // Calculates the number that is a power of 2 and lower than numPlayers.\n let countNodesUpperBound = Math.pow(2, upperPower);\n\n // Calculates the number that is a power of 2 and higher than numPlayers.\n let countNodesLowerBound = countNodesUpperBound / 2;\n\n // Determines the number of nodes that will not show in the 1st level.\n let countNodesHidden = numPlayers - countNodesLowerBound;\n\n // Enters the players for the 1st round.\n let currentPlayer = 0;\n for (let i = 0; i \u003c countNodesLowerBound; i++) {\n if (i \u003c countNodesHidden) {\n // Must be on the first level\n let rng = sheetResults.getRange(i * 4 + 1, 1);\n setBracketItem_(rng, players);\n setBracketItem_(rng.offset(2, 0, 1, 1), players);\n setConnector_(sheetResults, rng.offset(0, 1, 3, 1));\n setBracketItem_(rng.offset(1, 2, 1, 1));\n } else {\n // This player gets a bye.\n setBracketItem_(sheetResults.getRange(i * 4 + 2, 3), players);\n }\n }\n\n // Fills in the rest of the bracket.\n upperPower--;\n for (let i = 0; i \u003c upperPower; i++) {\n let pow1 = Math.pow(2, i + 1);\n let pow2 = Math.pow(2, i + 2);\n let pow3 = Math.pow(2, i + 3);\n for (let j = 0; j \u003c Math.pow(2, upperPower - i - 1); j++) {\n setBracketItem_(sheetResults.getRange((j * pow3) + pow2, i * 2 + 5));\n setConnector_(sheetResults, sheetResults.getRange((j * pow3) + pow1, i * 2 + 4, pow2 + 1, 1));\n }\n }\n}\n\n/**\n * Sets the value of an item in the bracket and the color.\n * @param {Range} rng The Spreadsheet Range.\n * @param {string[]} players The list of players.\n */\nfunction setBracketItem_(rng, players) {\n if (players) {\n let rand = Math.ceil(Math.random() * players.length);\n rng.setValue(players.splice(rand - 1, 1)[0][0]);\n }\n rng.setBackgroundColor('yellow');\n}\n\n/**\n * Sets the color and width for connector cells.\n * @param {Sheet} sheet The spreadsheet to setup.\n * @param {Range} rng The spreadsheet range.\n */\nfunction setConnector_(sheet, rng) {\n sheet.setColumnWidth(rng.getColumnIndex(), CONNECTOR_WIDTH);\n rng.setBackgroundColor('green');\n}\n```\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\nContributors\n------------\n\nThis sample is maintained by Google with the help of Google Developer Experts.\n\nNext steps\n----------\n\n- [Custom menus in Google Workspace](/apps-script/guides/menus)\n- [Extending Google Sheets](/apps-script/guides/sheets)"]]