javascript – How to select an entire HTML table in JS and copy it to clipboard

Question:

I have a simple (but long) HTML table that when selecting and copying ( CTRL + C ) to Excel pastes perfect.

I want to add a button that does this process so I don't have to manually select this huge table and simplify this process. I managed to copy the scripts to the clipboard, but playing the content by innerHTML inside a textarea and then copying it, but the source code goes and not the "result".

How can I give a "select();" in the table and CTRL + C without followed and reproduce the same desired effect of pasting in excel? abs

Answer:

I did some tests here and I have the following code – JSBIN :

NOTE: CSS is in JS BIN but is irrelevant for example.

JAVASCRIPT

var Tabela = {
  selecionarTabela: function(el) {
    var body = document.body, range, sel;
    if (document.createRange && window.getSelection) {
        range = document.createRange();
        sel = window.getSelection();
        sel.removeAllRanges();
        try {
            range.selectNodeContents(el);
            sel.addRange(range);
        } catch (e) {
            range.selectNode(el);
            sel.addRange(range);
        }
    } else if (body.createTextRange) {
        range = body.createTextRange();
        range.moveToElementText(el);
        range.select();
    }
    try {
      document.execCommand('copy');
      range.blur();
    } catch(error){
      // Exceção aqui
    }
  }
}

var selecionaTabelaBtn = document.querySelector("#selecionar-tabela");
var tabelaDeDados = document.querySelector("#minha-tabela");
// Seleciona a tabela no clique do botão
selecionaTabelaBtn.addEventListener("click", function(){
  Tabela.selecionarTabela(tabelaDeDados);
});

HTML5

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
  <body>
    <!-- Botão de seleção -->
    <button id="selecionar-tabela">Selecionar tabela</button>
    <!-- Tabela a ser selecionada -->
    <table id="minha-tabela">
        <thead>
            <tr>
              <th>Cabeçalho</th>
              <th>Cabeçalho</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td>Conteúdo</td>
            <td>Conteúdo</td>
          </tr>
          <tr>
            <td>Conteúdo</td>
            <td>Conteúdo</td>
          </tr>
          <tr>
            <td>Conteúdo</td>
            <td>Conteúdo</td>
          </tr>
        </tbody>
    </table>
    <!-- \\ Fim da tabela -->
  </body>
</html>
Scroll to Top