如何将数据从HTML保存到excel,点击“提交”即可;窗体按钮

How to save data from HTML to excel, on click on "submit" button of form?

本文关键字:提交 点击 即可 按钮 窗体 excel 数据 HTML 保存      更新时间:2023-09-26
<form>
  First name: <input type="text" name="fname"><br>
  Last name: <input type="text" name="lname"><br>
  <input type="submit" value="Submit">
</form>

我想点击"提交",它应该保存名字和姓氏在Excel表。我不想使用数据库,也没有服务器。我在某个地方读到,我们可以在CSV中做同样的事情。帮我一下。

一种可能的方法是创建一个html表。您可以将表单值设置为一个不可见的表,并通过链接模拟html表的下载。Excel读取html并显示数据。


的例子:

function exportF() {
  //Format your table with form data
  document.getElementById("input").innerHTML = document.getElementById("text").value;
  var table = document.getElementById("table");
  var html = table.outerHTML;
  var url = 'data:application/vnd.ms-excel,' + escape(html); // Set your html table into url 
  var link = document.getElementById("downloadLink");
  link.setAttribute("href", url);
  link.setAttribute("download", "export.xls"); // Choose the file name
  link.click(); // Download your excel file   
  return false;
}
<form onsubmit="return exportF()">
  <input id="text" type="text" />
  <input type="submit" />
</form>
<table id="table" style="display: none">
  <tr>
    <td id="input">
    </td>
  </tr>
</table>
<a style="display: none" id="downloadLink"></a>

允许生成.xlsx文件的库有很多,您需要选择其中一个(Google xlsx.js),在提交时读取表单中的值,然后使用您选择的库创建您希望的电子表格