Use js to convert html format table => excel format file

Export html format table as excel table file

  1. Download the auxiliary module first.
  2. Import the auxiliary module to the target html page
  3. Use DOM operations to get the content of the target table.
  4. Use the function of the auxiliary module to save the content as a table file.

1. Download auxiliary modules

Here I am using fileSaver, the address is:
https://github.com/kebingzao/fileSaver_excel
Download js (Blob, FileSaver) files, and put them into your project directory:Insert picture description here

2. Import the auxiliary module to the target html page

Insert picture description here

3. Use DOM operations to obtain table content

// 获取表格对象, 并保存为blob
    var blob = new Blob([document.getElementById('demo').outerHTML], {
    
    
    //  指定编码类型, 防止乱码
      type: "text/plain;charset=utf-8"
    });

4. Use the auxiliary module function to save the content as a table file.

    // 使用FileSaver的saveAs方法保存. 
    saveAs(blob,  "export.xls");

to sum up:

Complete code: The
page looks like this (the table object is obtained according to the id):

<table id="demo">
        <thead class="top">
            <td>名字</td>
            <td>性别</td>
            <td>年龄</td>
        </thead>
        <tr>
          <td>james</td>
          <td></td>
          <td>35</td>
        </tr>
        <tr>
          <td>kobe</td>
          <td></td>
          <td>42</td>
        </tr>
        <tr>
          <td>wade</td>
          <td></td>
          <td>35</td>
        </tr>
    </table>

js code:

<script>
  // 这里写的是点击函数, 方法为下面的
  $('.btn').on('click', () => {
    
    
  saveAsTable()
  }) 

  function saveAsTable() {
    
    
     // 获取表格对象
    var blob = new Blob([document.getElementById('demo').outerHTML], {
    
    
      type: "text/plain;charset=utf-8"
    });
    // 使用FileSaver的saveAs方法保存. 
    saveAs(blob,  "mangoo.xls");
  }
</script>

Final result:
mangoo.xls
Insert picture description here

There is no turning back in life, every step you take counts! Come on!!!

Guess you like

Origin blog.csdn.net/weixin_40944062/article/details/107537129