Guia de início rápido da biblioteca
Mantenha tudo organizado com as coleções
Salve e categorize o conteúdo com base nas suas preferências.
Crie uma biblioteca do Apps Script que pode ser usada para remover linhas duplicadas em dados de planilhas.
Objetivos
- Configure o script.
- Execute o script.
Pré-requisitos
Para usar esta amostra, você precisa atender aos seguintes pré-requisitos:
- Uma Conta do Google (as contas do Google Workspace podem exigir a aprovação do administrador).
- Um navegador da Web com acesso à Internet.
Configurar o script
Para criar a biblioteca, siga estas etapas:
- Faça login na sua Conta do Google.
- Para abrir o editor de script, acesse script.google.com.
- Na parte de cima à esquerda, clique em Novo projeto.
Apague o código no editor de script (se houver algum) e cole o código abaixo.
Clique em Salvar
.
No canto superior esquerdo, clique em Projeto sem título.
Nomeie o script como Remover linhas duplicadas e clique em Renomear.
Clique em Implantar > Nova implantação.
Ao lado de Selecionar tipo, clique em Habilitar tipos de implantação
> Biblioteca.
Insira uma descrição da biblioteca, como Remover linhas duplicadas. Qualquer pessoa com acesso à biblioteca pode ver essa descrição.
Clique em Implantar.
À esquerda, clique em Configurações do projeto
.
Em IDs, copie o ID do script para usar em uma etapa posterior.
Executar o script
Para usar uma biblioteca, você precisa ter pelo menos permissões de leitura para o projeto
do Apps Script dela. Como você criou a biblioteca, tem as permissões necessárias para usá-la. Se quiser permitir que outras pessoas usem a biblioteca, dê a elas permissão de leitura
para o projeto do Apps Script.
Para usar a biblioteca, siga estas etapas:
- Abra uma planilha Google com dados e linhas duplicadas. Para usar uma planilha de exemplo, faça uma cópia da planilha Exemplo de linhas duplicadas.
- Clique em Extensões > Apps Script.
- Ao lado de Bibliotecas, clique em Adicionar uma biblioteca
add.
- Na seção ID do script, cole o ID do script do projeto da biblioteca do Apps Script
que você copiou na seção anterior.
- Clique em Pesquisar.
- Na seção Versão, selecione 1.
- Clique em Adicionar.
Apague o código no editor de script (se houver algum) e cole o código abaixo.
function runLibrary() {
Removeduplicaterows.removeDuplicates();
}
No menu suspenso de função, selecione runLibrary.
Clique em Executar.
Volte para a planilha e confira os dados atualizados sem linhas duplicadas.
Revisar o código
Para revisar o código do Apps Script dessa solução, clique em Ver código-fonte abaixo:
Ver o código-fonte
Primeiro, o script faz uma única chamada à planilha para recuperar todos os dados. Você pode ler a planilha linha por linha, mas as operações do JavaScript são muito mais rápidas do que falar com outros serviços, como o Google Sheets. Quanto menos chamadas você fizer, mais rápido será o processo. Isso é importante porque cada execução de script tem um tempo máximo de execução de 6 minutos.
A variável data
é uma matriz bidimensional do JavaScript que contém todos os valores da planilha. newData
é uma matriz vazia em que o
script coloca todas as linhas não duplicadas.
O primeiro loop for
itera em cada linha da matriz bidimensional data
. Para cada linha, o segundo loop testa se outra linha com
dados correspondentes já existe na matriz newData
. Se não for um
duplicado, a linha será inserida na matriz newData
.
Por fim, o script exclui o conteúdo atual da planilha e insere o conteúdo da matriz newData
.
Modificações
Você pode editar a biblioteca o quanto quiser para atender às suas necessidades. Confira abaixo uma modificação opcional.
Remover linhas com dados correspondentes em algumas colunas
Em vez de remover linhas que correspondem totalmente, talvez você queira remover linhas com dados correspondentes em apenas uma ou duas das colunas. Para fazer isso, mude a
instrução condicional.
No exemplo de código, atualize a seguinte linha:
if(row.join() == newData[j].join()){
duplicate = true;
}
Substitua a linha pelo seguinte código:
if(row[0] == newData[j][0] && row[1] == newData[j][1]){
duplicate = true;
}
A instrução condicional acima encontra duplicatas sempre que duas linhas têm os mesmos dados na primeira e na segunda colunas da planilha.
Colaboradores
Esta amostra foi criada por Romain Vialard, um Google Developer Expert. Siga o Romain no Twitter @romain_vialard.
Esta amostra é mantida pelo Google com a ajuda dos Google Developer Experts.
Próximas etapas
Exceto em caso de indicação contrária, o conteúdo desta página é licenciado de acordo com a Licença de atribuição 4.0 do Creative Commons, e as amostras de código são licenciadas de acordo com a Licença Apache 2.0. Para mais detalhes, consulte as políticas do site do Google Developers. Java é uma marca registrada da Oracle e/ou afiliadas.
Última atualização 2025-08-31 UTC.
[null,null,["Última atualização 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)"]]