Bắt đầu nhanh về thư viện
Sử dụng bộ sưu tập để sắp xếp ngăn nắp các trang
Lưu và phân loại nội dung dựa trên lựa chọn ưu tiên của bạn.
Tạo một thư viện Apps Script mà bạn có thể dùng để xoá các hàng trùng lặp trong dữ liệu bảng tính.
Mục tiêu
- Thiết lập tập lệnh.
- Chạy tập lệnh.
Điều kiện tiên quyết
Để sử dụng mẫu này, bạn cần đáp ứng các điều kiện tiên quyết sau:
- Một Tài khoản Google (tài khoản Google Workspace có thể yêu cầu quản trị viên phê duyệt).
- Một trình duyệt web có quyền truy cập vào Internet.
Thiết lập tập lệnh
Để tạo thư viện, hãy thực hiện các bước sau:
- Đăng nhập vào Tài khoản Google của bạn.
- Để mở trình chỉnh sửa tập lệnh, hãy truy cập vào script.google.com.
- Ở trên cùng bên trái, hãy nhấp vào Dự án mới.
Xoá mọi mã trong trình chỉnh sửa tập lệnh rồi dán mã bên dưới vào.
Nhấp vào biểu tượng Lưu
.
Ở trên cùng bên trái, hãy nhấp vào Dự án không có tiêu đề.
Đặt tên cho tập lệnh là Xoá các hàng trùng lặp rồi nhấp vào Đổi tên.
Nhấp vào Triển khai > Triển khai mới.
Bên cạnh Chọn loại, hãy nhấp vào Bật các loại triển khai
> Thư viện.
Nhập nội dung mô tả cho thư viện, chẳng hạn như Xoá các hàng trùng lặp. Bất kỳ ai có quyền truy cập vào thư viện đều có thể xem nội dung mô tả này.
Nhấp vào Triển khai.
Ở bên trái, hãy nhấp vào Cài đặt dự án
.
Trong mục Mã nhận dạng, hãy sao chép mã nhận dạng tập lệnh để sử dụng ở bước sau.
Chạy tập lệnh
Để sử dụng một thư viện, bạn phải có ít nhất quyền xem đối với dự án Apps Script của thư viện đó. Vì bạn đã tạo thư viện này, nên bạn có các quyền cần thiết để sử dụng thư viện. Nếu bạn muốn cho phép người khác sử dụng thư viện, hãy cấp cho họ quyền xem đối với dự án Apps Script.
Để sử dụng thư viện này, hãy thực hiện các bước sau:
- Mở một bảng tính Google Trang tính có dữ liệu chứa các hàng trùng lặp. Để sử dụng bảng tính mẫu, hãy tạo bản sao của bảng tính Hàng trùng lặp mẫu.
- Nhấp vào Tiện ích > Apps Script.
- Bên cạnh Thư viện, hãy nhấp vào biểu tượng Thêm thư viện add.
- Trong phần Mã tập lệnh, hãy dán mã tập lệnh từ dự án Apps Script của thư viện mà bạn đã sao chép trong phần trước.
- Nhấp vào Tìm kiếm.
- Trong phần Phiên bản, hãy chọn 1.
- Nhấp vào Thêm.
Xoá mọi mã trong trình chỉnh sửa tập lệnh rồi dán mã bên dưới vào.
function runLibrary() {
Removeduplicaterows.removeDuplicates();
}
Trong trình đơn thả xuống hàm, hãy chọn runLibrary.
Nhấp vào Chạy.
Quay lại bảng tính để xem dữ liệu đã cập nhật mà không có các hàng trùng lặp.
Xem lại mã
Để xem lại mã Apps Script cho giải pháp này, hãy nhấp vào Xem mã nguồn bên dưới:
Xem mã nguồn
Trước tiên, tập lệnh sẽ gọi bảng tính một lần để truy xuất tất cả dữ liệu. Bạn có thể chọn đọc từng hàng trong trang tính, nhưng các thao tác JavaScript nhanh hơn đáng kể so với việc giao tiếp với các dịch vụ khác như Trang tính. Bạn càng thực hiện ít lệnh gọi, quá trình này càng diễn ra nhanh hơn. Điều này rất quan trọng vì mỗi lần thực thi tập lệnh có thời gian chạy tối đa là 6 phút.
Biến data
là một mảng 2 chiều của JavaScript chứa tất cả các giá trị trong trang tính. newData
là một mảng trống, nơi tập lệnh đặt tất cả các hàng không trùng lặp.
Vòng lặp for
đầu tiên lặp lại trên từng hàng trong mảng data
2 chiều. Đối với mỗi hàng, vòng lặp thứ hai sẽ kiểm tra xem có hàng nào khác có dữ liệu trùng khớp đã tồn tại trong mảng newData
hay không. Nếu không phải là một hàng trùng lặp, thì hàng đó sẽ được đẩy vào mảng newData
.
Cuối cùng, tập lệnh sẽ xoá nội dung hiện có của trang tính và chèn nội dung của mảng newData
.
Sửa đổi
Bạn có thể chỉnh sửa thư viện này theo ý muốn để phù hợp với nhu cầu của mình. Dưới đây là một nội dung sửa đổi không bắt buộc.
Xoá những hàng có dữ liệu trùng khớp ở một số cột
Thay vì xoá các hàng khớp hoàn toàn, bạn có thể muốn xoá các hàng có dữ liệu khớp ở một hoặc hai cột. Để làm việc đó, bạn có thể thay đổi câu lệnh có điều kiện.
Trong mã mẫu, hãy cập nhật dòng sau:
if(row.join() == newData[j].join()){
duplicate = true;
}
Thay thế dòng này bằng đoạn mã sau:
if(row[0] == newData[j][0] && row[1] == newData[j][1]){
duplicate = true;
}
Câu lệnh điều kiện ở trên sẽ tìm các giá trị trùng lặp mỗi khi 2 hàng có cùng dữ liệu trong cột đầu tiên và cột thứ hai của trang tính.
Người đóng góp
Mẫu này do Romain Vialard, một Chuyên gia phát triển của Google tạo ra. Theo dõi Romain trên Twitter @romain_vialard.
Mẫu này do Google duy trì với sự trợ giúp của các Chuyên gia Google về phát triển.
Các bước tiếp theo
Trừ phi có lưu ý khác, nội dung của trang này được cấp phép theo Giấy phép ghi nhận tác giả 4.0 của Creative Commons và các mẫu mã lập trình được cấp phép theo Giấy phép Apache 2.0. Để biết thông tin chi tiết, vui lòng tham khảo Chính sách trang web của Google Developers. Java là nhãn hiệu đã đăng ký của Oracle và/hoặc các đơn vị liên kết với Oracle.
Cập nhật lần gần đây nhất: 2025-08-31 UTC.
[null,null,["Cập nhật lần gần đây nhất: 2025-08-31 UTC."],[[["\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)"]]