简体   繁体   中英

How to save Html table data in .txt file?

This is my Html Table.

<table>
  <thead>
    <tr>
      <th>First Name</th>
      <th>Last Name</th>
      <th>Email Id</th>
      <th>Phone Number</th>
      <th>Prefered Contact</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>James</td>
      <td>Miles</td>
      <td>james@abcd.com</td>
      <td>9876543210</td>
      <td>email</td>
    </tr>
    <tr>
      <td>John</td>
      <td>Paul</td>
      <td>john@abcd.com</td>
      <td>9638527410</td>
      <td>phone</td>
    </tr>
    <tr>
      <td>Math</td>
      <td>willams</td>
      <td>Math@abcd.com</td>
      <td>99873210456</td>
      <td>phone</td>
    </tr>
  </tbody>
</table>

In this table there is Save Button.

<input type="button" id="txt" value="Save" />

Button Code

function tableToJson(table) {
  var data=[];
  var headers=[];
  for (var i=0;
  i < table.rows[0].cells.length;
  i++) {
    headers[i]=table.rows[0].cells[i].innerHTML.toLowerCase().replace(/ /gi, '');
  }
  for (var i=1;
  i < table.rows.length;
  i++) {
    var tableRow=table.rows[i];
    var rowData= {}
    ;
    for (var j=0;
    j < tableRow.cells.length;
    j++) {
      rowData[headers[j]]=tableRow.cells[j].innerHTML;
    }
    data.push(rowData);
  }
  return data;
}

When the click the save button, The html table data will stored in the .txt document without <table> , <tr> , <td> . The data storing format will be like below format.

(James,Miles,james@abcd.com,9876543210,email),
(John,Paul,john@abcd.com,9638527410,phone),
(Math,willams,Math@abcd.com,99873210456,phone)

Slightly clearer code than the above answer that works for any number of columns

var retContent = [];
var retString = '';
$('tbody tr').each(function (idx, elem)
{
  var elemText = [];
  $(elem).children('td').each(function (childIdx, childElem)
  {
    elemText.push($(childElem).text());
  });
  retContent.push(`(${elemText.join(',')})`);
});
retString = retContent.join(',\r\n');

jsfiddle with the full code

First of all, you have to create data which contains all user details.

userDetails='';
$('table tbody tr').each(function(){
   var detail='(';
   $(this).find('td').each(function(){
        detail+=$(this).html()+',';
   });
   detail=detail.substring(0,detail.length-1);
   detail+=')';
   userDetails+=detail+"\r\n";
});

Then you need to save file:

var a=document.getElementById('save');
a.onclick=function(){
    var a = document.getElementById("save");
    var file = new Blob([userDetails], {type: 'text/plain'});
    a.href = URL.createObjectURL(file);
    a.download = "data.txt";
}

Here is a working solution: jsfiddle .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM