javascript 如何将数据从 HTML 保存到 Excel,点击表单的“提交”按钮?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30346942/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to save data from HTML to excel, on click on "submit" button of form?
提问by user2842328
<form>
First name: <input type="text" name="fname"><br>
Last name: <input type="text" name="lname"><br>
<input type="submit" value="Submit">
</form>
I want onclick "submit" it should save first name and last name in Excel sheet. I don't want to use database and I don't have any server. I read somewhere that we can do the same in CSV. Help me out.
我想点击“提交”,它应该在 Excel 工作表中保存名字和姓氏。我不想使用数据库,我没有任何服务器。我在某处读到我们可以在 CSV 中做同样的事情。帮帮我。
Thanks in advance.
提前致谢。
回答by R3tep
A possible way is to create an html table. You can set the form values into an invisible table and simulate the download of html table with a link. Excel reads the html and display the data.
一种可能的方法是创建一个 html 表。您可以将表单值设置为一个不可见的表格,并通过链接模拟 html 表格的下载。Excel 读取 html 并显示数据。
Example :
例子 :
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>
回答by David Mulder
There are various libraries that allow the generation of .xlsx
files, you will need to pick one of them (Google xlsx.js
), read out the values in the form on submit and then create the spreadsheet you wish using the library you picked.
有各种允许生成.xlsx
文件的库,您需要选择其中之一 (Google xlsx.js
),在提交时读出表单中的值,然后使用您选择的库创建您想要的电子表格。