库快速入门
使用集合让一切井井有条
根据您的偏好保存内容并对其进行分类。
构建一个 Apps 脚本库,您可以使用该库移除电子表格数据中的重复行。
目标
前提条件
如需使用此示例,您需要满足以下前提条件:
- Google 账号(Google Workspace 账号可能需要管理员批准)。
- 可访问互联网的网络浏览器。
设置脚本
如需构建库,请按以下步骤操作:
- 登录您的 Google 账号。
- 如需打开脚本编辑器,请前往 script.google.com。
- 点击左上角的新项目。
删除脚本编辑器中的所有代码,然后粘贴以下代码。
点击“保存”图标
。
点击左上角的未命名项目。
将脚本命名为 Remove duplicate rows,然后点击重命名。
依次点击部署 > 新部署。
点击选择类型旁边的“启用部署类型”图标
> 库。
输入库的说明,例如移除重复行。有权访问该库的任何用户均可查看此说明。
点击部署。
点击左侧的项目设置图标
。
在 ID 下,复制脚本 ID 以用于后续步骤。
运行脚本
如需使用某个库,您必须至少拥有该库的 Apps 脚本项目的查看权限。由于您创建了该库,因此您拥有使用该库所需的权限。如果您想让其他人使用该脚本库,请向他们授予对相应 Apps 脚本项目的查看权限。
如需使用该库,请按以下步骤操作:
- 打开包含重复行的 Google 表格电子表格。如需使用示例电子表格,请复制“示例 - 重复行”电子表格。
- 依次点击扩展程序 > Google Apps 脚本。
- 点击媒体库旁边的“添加媒体库”图标 add。
- 在脚本 ID 部分中,粘贴您在上一部分中复制的库 Apps 脚本项目中的脚本 ID。
- 点击查找。
- 在版本部分中,选择 1。
- 点击添加。
删除脚本编辑器中的所有代码,然后粘贴以下代码。
function runLibrary() {
Removeduplicaterows.removeDuplicates();
}
在函数下拉菜单中,选择 runLibrary。
点击运行。
返回电子表格,查看更新后的数据(不含重复行)。
查看代码
如需查看此解决方案的 Apps 脚本代码,请点击下方的查看源代码:
查看源代码
首先,脚本会向电子表格发出一次调用,以检索所有数据。您可以选择逐行读取工作表,但 JavaScript 操作比与电子表格等其他服务通信快得多。您发出的调用越少,速度就越快。这一点很重要,因为每次脚本执行的最长运行时间为 6 分钟。
变量 data
是一个 JavaScript 二维数组,其中包含工作表中的所有值。newData
是一个空数组,脚本会将所有非重复行放入其中。
第一个 for
循环会遍历 data
二维数组中的每一行。对于每一行,第二个循环会测试 newData
数组中是否已存在具有匹配数据的另一行。如果不是重复项,则将相应行推送到 newData
数组中。
最后,该脚本会删除工作表的现有内容,并插入 newData
数组的内容。
修改
您可以根据需要随意修改库。以下是可选的修改。
移除某些列中包含匹配数据的行
您可能不想移除完全匹配的行,而是只想移除仅在一两列中包含匹配数据的行。为此,您可以更改条件语句。
在示例代码中,更新以下行:
if(row.join() == newData[j].join()){
duplicate = true;
}
将该行替换为以下代码:
if(row[0] == newData[j][0] && row[1] == newData[j][1]){
duplicate = true;
}
上述条件语句会在工作表的第一列和第二列中出现相同数据的两个行时查找重复项。
贡献者
此示例由 Google 开发者专家 Romain Vialard 创建。在 Twitter 上关注 Romain (@romain_vialard)。
此示例由 Google 在 Google 开发者专家的帮助下维护。
后续步骤
如未另行说明,那么本页面中的内容已根据知识共享署名 4.0 许可获得了许可,并且代码示例已根据 Apache 2.0 许可获得了许可。有关详情,请参阅 Google 开发者网站政策。Java 是 Oracle 和/或其关联公司的注册商标。
最后更新时间 (UTC):2025-08-31。
[null,null,["最后更新时间 (UTC):2025-08-31。"],[[["\u003cp\u003eThis guide provides step-by-step instructions to create an Apps Script library that removes duplicate rows from Google Sheets data.\u003c/p\u003e\n"],["\u003cp\u003eThe library uses a JavaScript function to identify and remove duplicate rows by comparing all column values within each row.\u003c/p\u003e\n"],["\u003cp\u003eUsers need a Google Account and a web browser to implement this solution, which involves setting up, deploying, and running the script within a spreadsheet.\u003c/p\u003e\n"],["\u003cp\u003eThe provided code can be modified to remove rows based on matching data in specific columns, enhancing the library's functionality.\u003c/p\u003e\n"]]],[],null,["# Library quickstart\n\nBuild an [Apps Script library](/apps-script/guides/libraries) that you can use to remove duplicate rows in spreadsheet data.\n\nObjectives\n----------\n\n- Set up the script.\n- Run the script.\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\nTo build the library, take the following steps:\n\n1. Sign in to your Google Account.\n2. To open the script editor, go to [script.google.com](https://script.google.com/home).\n3. At the top left, click **New project**.\n4. Delete any code in the script editor and paste in the code below.\n\n sheets/removingDuplicates/removingDuplicates.gs \n [View on GitHub](https://github.com/googleworkspace/apps-script-samples/blob/main/sheets/removingDuplicates/removingDuplicates.gs) \n\n ```javascript\n /**\n * Removes duplicate rows from the current sheet.\n */\n function removeDuplicates() {\n const sheet = SpreadsheetApp.getActiveSheet();\n const data = sheet.getDataRange().getValues();\n const uniqueData = {};\n for (let row of data) {\n const key = row.join();\n uniqueData[key] = uniqueData[key] || row;\n }\n sheet.clearContents();\n const newData = Object.values(uniqueData);\n sheet.getRange(1, 1, newData.length, newData[0].length).setValues(newData);\n }\n ```\n5. Click Save .\n\n6. At the top left, click **Untitled project**.\n\n7. Name your script **Remove duplicate rows** and click **Rename**.\n\n8. Click **Deploy** \\\u003e **New deployment**.\n\n9. Next to **Select type** click Enable deployment types\n\n \\\u003e **Library**.\n\n10. Enter a description of the library, such as **Remove duplicate rows**. Anyone\n with access to the library can view this description.\n\n11. Click **Deploy**.\n\n12. At the left, click **Project settings** .\n\n13. Under **IDs**, copy the script ID for use in a later step.\n\nRun the script\n--------------\n\nTo use a library, you must have at least view permissions for its\nApps Script project. Since you created the library, you have the\nrequired permissions\nto use it. If you want to let others use the library, give them view permission\nfor the Apps Script project.\n\nTo use the library, take the following steps:\n\n1. Open a Google Sheets spreadsheet that has data with duplicate rows. To use a sample spreadsheet, [make a copy of the **Sample duplicate rows** spreadsheet](https://docs.google.com/spreadsheets/d/1_Tcb0kokQIYCEz_nWnxUHZp8nwTysjjxucMmVZ0DeSg/copy?usp=sharing).\n2. Click **Extensions** \\\u003e **Apps Script**.\n3. Next to **Libraries** , click Add a library add.\n4. In the **Script ID** section, paste the script ID from the library Apps Script project you copied in the previous section.\n5. Click **Look up**.\n6. In the **Version** section, select **1**.\n7. Click **Add**.\n8. Delete any code in the script editor and paste in the code below.\n\n function runLibrary() {\n Removeduplicaterows.removeDuplicates();\n }\n\n9. In the function dropdown, select **runLibrary**.\n\n10. Click **Run**.\n\n11. Return to the spreadsheet to view the updated data without duplicate rows.\n\nReview the code\n---------------\n\nTo review the Apps Script code for this solution, click **View source code**\nbelow: \n\n#### View the source code\n\n\nFirst, the script makes a single call to the spreadsheet to retrieve all the\ndata. You can choose to read the sheet row by row, but JavaScript operations are\nconsiderably faster than talking to other services like Spreadsheet. The fewer\ncalls you make, the faster it goes. This is important because each script\nexecution has a maximum run time of 6 minutes. \nsheets/removingDuplicates/removingDuplicates.gs \n[View on GitHub](https://github.com/googleworkspace/apps-script-samples/blob/main/sheets/removingDuplicates/removingDuplicates.gs) \n\n```javascript\nconst sheet = SpreadsheetApp.getActiveSheet();\nconst data = sheet.getDataRange().getValues();\n```\n\n\nThe variable `data` is a JavaScript 2-dimensional array that contains\nall the values in the sheet. `newData` is an empty array where the\nscript puts all the non-duplicate rows. \nsheets/removingDuplicates/removingDuplicates.gs \n[View on GitHub](https://github.com/googleworkspace/apps-script-samples/blob/main/sheets/removingDuplicates/removingDuplicates.gs) \n\n```javascript\nconst newData = Object.values(uniqueData);\n```\n\n\nThe first `for` loop iterates over each row in the `data`\n2-dimensional array. For each row, the second loop tests if another row with\nmatching data already exists in the `newData` array. If it's not a\nduplicate, the row is pushed into the `newData` array. \nsheets/removingDuplicates/removingDuplicates.gs \n[View on GitHub](https://github.com/googleworkspace/apps-script-samples/blob/main/sheets/removingDuplicates/removingDuplicates.gs) \n\n```javascript\nuniqueData[key] = uniqueData[key] || row;\n```\n\n\nFinally, the script deletes the existing content of the sheet and inserts\nthe content of the `newData` array. \nsheets/removingDuplicates/removingDuplicates.gs \n[View on GitHub](https://github.com/googleworkspace/apps-script-samples/blob/main/sheets/removingDuplicates/removingDuplicates.gs) \n\n```javascript\nsheet.clearContents();\nconst newData = Object.values(uniqueData);\nsheet.getRange(1, 1, newData.length, newData[0].length).setValues(newData);\n```\n\nModifications\n-------------\n\nYou can edit the library as much as you'd like to fit your needs. Below is an\noptional modification. \n\n#### Remove rows with matching data in some columns\n\n\nInstead of removing rows that match entirely, you might want to remove rows with\nmatching data in just one or two of the columns. To do that, you can change the\nconditional statement.\n\n\nIn the sample code, update the following line: \n\n```transact-sql\n if(row.join() == newData[j].join()){\n duplicate = true;\n }\n```\n\n\nReplace the line with the following code: \n\n```transact-sql\n if(row[0] == newData[j][0] && row[1] == newData[j][1]){\n duplicate = true;\n }\n```\n\n\nThe above conditional statement finds duplicates each time two rows have the\nsame data in the first and second columns of the sheet.\n\nContributors\n------------\n\nThis sample was created by Romain Vialard, a Google Developer Expert. Follow\nRomain on Twitter [@romain_vialard](https://twitter.com/romain_vialard).\n\nThis sample is maintained by Google with the help of Google Developer Experts.\n\nNext steps\n----------\n\n- [Libraries](/apps-script/guides/libraries)\n- [Create and manage deployments](/apps-script/concepts/deployments)"]]