Importing an HTML Table into a Database

0

Hello, I'm a beginner in Django and JS. I'm having a lot of work to import an HTML table into a SQL database. Can you do that?

Would it be better to collect this data and import it directly through html or better with a backend? If so, how would you do that?

 <input type="text" placeholder="Digite para buscar" id="filtro_tabela"/>
 <table id="tabela_dados">
 <tr>
    <th id ="nome" name="nome">Nome</th>
    <th id ="idade name="idade"">idade</th>
    <th id ="sexo" name="sexo"">sexo</th>
 </tr>
  <tr>
    <td>Gian Nunes</td>
    <td>29</td>
    <td>Masculino</td>
 </tr>
 <tr>
    <td>Gabriel Dionizio</td>
    <td>25</td>
    <td>Masculino</td>
 </tr>
 <tr>
    <td>Júlia da Silva</td>
    <td>24</td>
    <td>Feminino</td>
 </tr>
  <tr>
    <td>Rebeca da Silva</td>
    <td>12</td>
    <td>Feminino</td>
 </tr>
  <tr>
    <td>Maria da Silva</td>
    <td>12</td>
    <td>Feminino</td>
 </tr>
  <tr>
    <td>João da Silva</td>
    <td>12</td>
    <td>Feminino</td>
 </tr>
</table>
    
asked by anonymous 08.11.2018 / 03:52

1 answer

1

In order for JS to capture the fields in the table, you must get all the text of the tds

/* Convert a data from a table to plain object
 * @param {tableId} table id to convert
 * @param {schemaObject} objectPlain with key as headName and value as Cell idx
 */ 
const getDataFromTable = (tableId, schemaObject) => {
  const table = document.getElementById(tableId);
  const trChilds = table.getElementsByTagName('tr');
  
  const lengthTr = trChilds.length;
  let datas = [];
  let data = {};
  let tdChilds = undefined;
  
  // ignore 0 is header
  for(let i = 1; i < lengthTr; i++) {
    data = {};
    tdChilds = trChilds[i].getElementsByTagName('td');

    // check that row has 3 cells
    // if false, read next row
    if(tdChilds.length !== 3) {
      continue;
    }

    // get all data from row and insert on data
    Object.keys(schemaObject).forEach((key) => data[key] = tdChilds[schemaObject[key]].innerText);
    datas.push(data);
  }
  
  return datas;
}

console.log(getDataFromTable('tabela_dados', { name: 0, age: 1, sex: 2}));
<input type="text" placeholder="Digite para buscar" id="filtro_tabela"/>
 <table id="tabela_dados">
 <tr>
    <th id ="nome" name="nome">Nome</th>
    <th id ="idade" name="idade">idade</th>
    <th id ="sexo" name="sexo">sexo</th>
 </tr>
  <tr>
    <td>Gian Nunes</td>
    <td>29</td>
    <td>Masculino</td>
 </tr>
 <tr>
    <td>Gabriel Dionizio</td>
    <td>25</td>
    <td>Masculino</td>
 </tr>
 <tr>
    <td>Júlia da Silva</td>
    <td>24</td>
    <td>Feminino</td>
 </tr>
  <tr>
    <td>Rebeca da Silva</td>
    <td>12</td>
    <td>Feminino</td>
 </tr>
  <tr>
    <td>Maria da Silva</td>
    <td>12</td>
    <td>Feminino</td>
 </tr>
  <tr>
    <td>João da Silva</td>
    <td>12</td>
    <td>Feminino</td>
 </tr>
</table>

To send to the back vc you can send the data to the back of the fetch ( link )

    
08.11.2018 / 09:55