如何在Javascript中读取CSV文件

How to read CSV file in Javascript

本文关键字:读取 CSV 文件 Javascript      更新时间:2023-09-26

我需要我的代码能够从csv文件中获取数据并将其打印到屏幕上。目前,它从文本文件中获取数据,但CSV只会返回"文件不支持"。这是我的代码。

<html>
<div id="page-wrapper">
        <div>
            Select a text file: 
            <input type="file" id="fileInput">
        </div>
        <pre id="fileDisplayArea"><pre>
    </div>
    <button onClick="test()">Show Text</button>
<script>
function test (){
    var file = fileInput.files[0];
var textType = /text.*/;
    if (file.type.match(textType)) {
  var reader = new FileReader();
  reader.onload = function(e) {
    var look = reader.result;
    window.alert (look);
  }
  reader.readAsText(file);  
} else {
  fileDisplayArea.innerText = "File not supported!";
}
}

</script>

file对象的type属性是操作系统根据文件的扩展名提供的类型。

在windows上,csv文件的filetypeapplication/vnd.ms-excel,所以当你检查:

file.type.match(/text.*/)

它是假的。

您可以使用更改代码来检查text.*application/vnd.ms-excel:

var textType = /text.*/;
var csvType = 'application/vnd.ms-excel';
if (file.type.match(textType) || file.type == csvType) {

另一个选项是检查文件的扩展名:

if (file.name.endsWith('.csv')) {
    ...
}