javascript - 从 HTML 输入数据生成 CSV 文件
问题描述
我试图以 HTML 形式将用户输入的数据传递给本地驱动器上的 csv 文件。但似乎其中有些错误。
即使是从其他来源复制的,我也尝试过下面的代码。
<html>
<head>
<script language="javascript">
function WriteToFile(passForm) {
var fso = new ActiveXObject("Scripting.FileSystemObject");
var fileLoc = "C:\\sample.txt";
var file = OpenTextFile(fileLoc,2,true,0);
file.write("File handling in Javascript");
file.Close();
alert('File created successfully at location: ' + fileLoc);
}
</script>
</head>
<body>
<p>create a csv file with following details -</p>
<form>
Type your first name: <input type="text" name="FirstName" size="20"><br>
Type your last name: <input type="text" name="LastName" size="20"><br>
<input type="button" value="submit" onclick="WriteToFile(this.form)">
</form>
</body>
</html>
</br></br></html>
CSV 文件没有被创建并且不能在 HTML 中得到任何错误。
解决方案
您没有使用变量 fso 来调用 OpenTextFile,您还应该记住 IE 有权在路径中写入
这应该适合你:
<html>
<head>
<script language="javascript">
function WriteToFile(passForm) {
var fso = new ActiveXObject("Scripting.FileSystemObject");
var fileLoc = "C:\\Users\\yourUser\\sample.csv";
var file = fso.OpenTextFile(fileLoc,2,true,0);
file.write("File handling in Javascript");
file.Close();
alert('File created successfully at location: ' + fileLoc);
}
</script>
</head>
<body>
<p>create a csv file with following details -</p>
<form>
Type your first name: <input type="text" name="FirstName" size="20"><br>
Type your last name: <input type="text" name="LastName" size="20"><br>
<input type="button" value="submit" onclick="WriteToFile(this.form)">
</form>
</body>
</html>
您还可以使用适用于多种浏览器的此解决方案:
<html>
<head>
<script language="javascript">
function downloadCSV(form) {
const content = 'Write your csv content here!!';
const mimeType = 'text/csv;encoding:utf-8';
const fileName = 'download.csv';
const a = document.createElement('a');
if (navigator.msSaveBlob) { // IE10
navigator.msSaveBlob(new Blob([content], {
type: mimeType
}), fileName);
} else if (URL && 'download' in a) { //html5 A[download]
a.href = URL.createObjectURL(new Blob([content], {
type: mimeType
}));
a.setAttribute('download', fileName);
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
} else {
location.href = 'data:application/octet-stream,' + encodeURIComponent(content); // only this mime type is supported
}
}
</script>
</head>
<body>
<p>create a csv file with following details -</p>
<form>
Type your first name: <input type="text" name="FirstName" size="20"><br>
Type your last name: <input type="text" name="LastName" size="20"><br>
<input type="button" value="submit" onclick="downloadCSV(this.form)">
</form>
</body>
</html>
推荐阅读
- ios - 在Objective-C中覆盖.h文件中的静态常量int?
- keras - Keras:如何实现 fcn 结构?
- javascript - JavaScript Bind (this) 不访问类
- curl - 如何使用 LINE Notify 发送多张图片
- javascript - useState 似乎无法正确映射数组
- c++ - 如何访问 std::sub_match 中的正则表达式搜索结果?
- django - 更新 Web 应用程序的最佳工作流程是什么
- python - 什么是 tensorflow.python.ops
- vue.js - 更新缓存 vue-apollo 后缺少字段
- assembly - 为什么 GCC 选择 dword movl 将长移位计数复制到 CL?