程式庫快速入門導覽課程
透過集合功能整理內容
你可以依據偏好儲存及分類內容。
建立 Apps Script 程式庫,用來移除試算表資料中的重複資料列。
目標
必要條件
如要使用這個範例,您必須符合下列先決條件:
- Google 帳戶 (Google Workspace 帳戶可能需要管理員核准)。
- 可連上網際網路的網路瀏覽器。
設定指令碼
如要建構程式庫,請按照下列步驟操作:
- 登入 Google 帳戶。
- 如要開啟指令碼編輯器,請前往 script.google.com。
- 按一下左上方的「新專案」。
刪除指令碼編輯器中的任何程式碼,然後貼上下列程式碼。
按一下「儲存」圖示
。
按一下左上方的「未命名專案」。
將指令碼命名為「Remove duplicate rows」(移除重複的資料列),然後按一下「Rename」(重新命名)。
依序點選「Deploy」(部署) >「New deployment」(新部署作業)。
按一下「選取類型」旁的「啟用部署類型」
>「程式庫」。
輸入程式庫的說明,例如「移除重複的列」。任何有權存取媒體庫的使用者都能查看這項說明。
按一下 [Deploy] (部署)。
按一下左側的「專案設定」圖示
。
在「ID」下方,複製指令碼 ID,供後續步驟使用。
執行指令碼
如要使用程式庫,您必須至少擁有該程式庫 Apps Script 專案的檢視權限。由於您是資料庫的建立者,因此擁有使用資料庫的
必要權限
。如要允許其他人使用程式庫,請授予他們 Apps Script 專案的檢視權限。
如要使用程式庫,請按照下列步驟操作:
- 開啟含有重複資料列的 Google 試算表。如要使用範例試算表,請複製「Sample duplicate rows」(重複資料列範例) 試算表。
- 依序點選「擴充功能」>「Apps Script」。
- 按一下「程式庫」旁的「新增程式庫」圖示 add。
- 在「指令碼 ID」部分,貼上您在上一個部分複製的程式庫 Apps Script 專案指令碼 ID。
- 按一下「查詢」。
- 在「版本」部分中,選取「1」。
- 按一下 [新增]。
刪除指令碼編輯器中的任何程式碼,然後貼上下列程式碼。
function runLibrary() {
Removeduplicaterows.removeDuplicates();
}
在函式下拉式選單中,選取「runLibrary」runLibrary。
按一下「執行」。
返回試算表,查看更新後的資料 (不含重複的資料列)。
檢查程式碼
如要查看這項解決方案的 Apps Script 程式碼,請按一下下方的「查看原始碼」:
查看原始碼
首先,指令碼會對試算表進行單一呼叫,以擷取所有資料。您可以選擇逐列讀取工作表,但 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 開發人員專家協助。
後續步驟
除非另有註明,否則本頁面中的內容是採用創用 CC 姓名標示 4.0 授權,程式碼範例則為阿帕契 2.0 授權。詳情請參閱《Google Developers 網站政策》。Java 是 Oracle 和/或其關聯企業的註冊商標。
上次更新時間:2025-08-31 (世界標準時間)。
[null,null,["上次更新時間: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)"]]