如何使用 JavaScript 从 *.CSV 文件中读取数据?

javascriptobject oriented programmingfront end technology

在本文中,我们将学习如何使用 JavaScript 从 *.CSV 文件中读取数据。

要将 CSV 数据转换或解析为数组,我们需要 JavaScript 的 FileReader 类,其中包含一个名为 readAsText() 的方法,该方法将读取 CSV 文件内容并将结果解析为字符串文本。

如果我们有字符串,我们可以创建一个自定义函数将字符串转换为数组。

要读取 CSV 文件,首先我们需要接受该文件。

现在让我们看看如何使用 HTML 元素从浏览器接受 csv 文件。

示例

以下是从浏览器接受 csv 文件的示例程序。

<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <form id="myForm"> <input type="file" id="csvFile" accept=".csv" /> <br /> <input type="submit" value="Submit" /> </form> </body> </html>

现在我们可以选择一个需要读取的 csv 文件。

现在让我们编写一个 JavaScript 代码来读取所选的 csv 文件。

示例

以下是示例程序,它接受并读取 csv 文件。

<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <form id="myForm"> <input type="file" id="csvFile" accept=".csv" /> <br /> <input type="submit" value="Submit" /> </form> <script> const myForm = document.getElementById("myForm"); const csvFile = document.getElementById("csvFile"); myForm.addEventListener("submit", function (e) { e.preventDefault(); const input = csvFile.files[0]; const reader = new FileReader(); reader.onload = function (e) { const text = e.target.result; document.write(text); }; reader.readAsText(input); }); </script> </body> </html>

相关文章