读取 CSV 文件的最后一行并提取一行

Read the last line of a CSV file and extract one row

我正在编写一个 javascpript 程序来从 CSV 文件中读取数据并将其放入变量中,最终显示在 HTML 中。该文件将由另一个程序附加到文件末尾。我只想读最后一行。

示例数据: 日期、数据 1、数据 2、数据 3

我找到了从最后一行读取一个值的其他代码... Read the last line of a CSV file and extract one value

我可以从那个代码中删除这个吗:

var fields = lastLine.split(',');
var audioFile = fields.slice(-1)[0].replace('file:\\', '')

谢谢!

这是我要使用的代码示例:

<html>
<head>
<script type="text/javascript">
$(document).ready(function() {
 // AJAX in the data file
    $.ajax({
        type: "GET",
        url: "file:///home/tech/Desktop/Test/data.csv",
        dataType: "text",
        success: function(data) {processData(data);}
        });

    // Let's process the data from the data file
    function processData(data) {
        var lines = data.trim().split('\n');
        var lastLine = lines.slice(-1)[0];

        //Set up the data arrays
        var date = [];
        var data1 = [];  
        var data2 = [];
        var data3 = [];


        for (var j=1; j<lines.length; j++) {
        var values = lines[j].split(','); // Split up the comma 
        seperated values
           // We read the key,1st, 2nd and 3rd rows 
           date.push(values[0]); // Read in as string
           // Recommended to read in as float, since we'll be doing 
           some operations on this later.
           data1.push(parseFloat(values[1])); 
           data2.push(parseFloat(values[2]));
           data3.push(parseFloat(values[3]));



        }
    }
})
</script>
</head>
<p>
<H1> This is the 
      <script type="text/javascript"> document.write(date()); 
</script> Date. </H1> <br>
<H1> This is the 
    <script type="text/javascript"> document.write(data1()); 
</script> Data1. </H1> <br>
<H1> This is the
    <script type="text/javascript"> document.write(data2()); 
</script> Data2. </H1> <br>
<H1> This is the
    <script type="text/javascript"> document.write(data3()); 
</script> Data3. </H1> <br>
</p>
</html>

您的代码存在一些问题,我在下面的代码中解决了这些问题

  1. 您的评论 seperated values 正在作为代码读取。
  2. 如果 CSV 中只有 1 行,您当前的代码将无法工作
  3. 你在字符串中间使用 <script> 标签是一个非常糟糕的习惯。

方案一(原地替换)

HTML

<section>
  <h1>This is the <span id="output0"></span> Date.</h1>
  <h1>This is the <span id="output1"></span> Data 1.</h1>
  <h1>This is the <span id="output2"></span> Data 2.</h1>
  <h1>This is the <span id="output3"></span> Data 3.</h1>
</section>

JavaScript

$(document).ready(function() {
  $.ajax({
    type: "GET",
    url: "data.csv",
    dataType: "text",
    success: function(data) {processData(data)}
  });

  function processData(data) {
    var lines = data.trim().split('\n');
    var lastLine = lines[lines.length - 1].split(',');

    lastLine.forEach(function(value, i) {
      var outputTarget = document.getElementById(`output${i}`);

      if (outputTarget) {
        outputTarget.innerHTML = value
      }
    })
  }
})

解决方案 2(在 JavaScript 内构建)

HTML

<section id="output"></section>

JavaScript

$(document).ready(function() {
  $.ajax({
    type: "GET",
    url: "data.csv",
    dataType: "text",
    success: function(data) {processData(data)}
  });

  function processData(data) {
    var lines = data.trim().split('\n');
    var lastLine = lines[lines.length - 1].split(',');
    var outputTarget = document.getElementById('output')

    lastLine.forEach(function(value, i) {
      var h1 = document.createElement('h1');

      switch(i) {
        case 0:
          h1.innerHTML = `This is the ${value} Date.`;
          break;
        default:
          h1.innerHTML = `This is the ${value} Data ${i}`
      }

      outputTarget.appendChild(h1);
    });
  }
})

如果我理解你的问题,你必须提出:

1) 在本地主机中将文件 csv(在此示例中为 test.csv)并将文件 js 放入服务器网络(示例 XAMPP)
2)你的4个数组date,data1,data2,dat3在函数外。
3) 我在所有 H1 标签中使用了 id 并用 document.getElementById...

调用它们

我尝试了代码并且有效。我没有用过parseFloat因为我有文本数据没有数字然后你记得修改代码...

代码如下:

<!DOCTYPE html>
<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">

//Set up the data arrays here
        var date = [];
        var data1 = [];
        var data2 = [];
        var data3 = [];

$(document).ready(function() {
 // AJAX in the data file
    $.ajax({
        type: "GET",
        //url: "file:///home/tech/Desktop/Test/test.csv",
        url: "test.csv",
        dataType: "text",
        success: function(data) {processData(data);}
        });

    // Let's process the data from the data file
    function processData(data) {
        var lines = data.trim().split('\n');
        var lastLine = lines.slice(-1)[0];
    /*
        //Set up the data arrays
        var date = [];
        var data1 = [];
        var data2 = [];
        var data3 = [];
    */

        for (var j=1; j<lines.length; j++) {
        var values = lines[j].split(','); // Split up the comma
        //seperated values
           // We read the key,1st, 2nd and 3rd rows
           date.push(values[0]); // Read in as string

           // Recommended to read in as float, since we'll be doing
           //some operations on this later.
           data1.push(values[1]);
           data2.push(values[2]);
           data3.push(values[3]);
        }
    //added code
    document.getElementById("date").innerHTML="This is the Date. " + date[date.length-1];
    document.getElementById("data1").innerHTML="This is the Data1. " + data1[data1.length-1];
    document.getElementById("data2").innerHTML="This is the Data2. " + data2[data2.length-1];
    document.getElementById("data3").innerHTML="This is the Data3. " + data3[data3.length-1];
    }
})
</script>
</head>
<p>
<H1 id="date"> 
      <script type="text/javascript"> 
</script>  </H1> <br>
<H1 id="data1"> 
    <script type="text/javascript"> 
</script> . </H1> <br>
<H1 id="data2"> 
    <script type="text/javascript"> 
</script> </H1> <br>
<H1 id="data3"> 
    <script type="text/javascript"> 
</script></H1> <br>
</p>
</html>

希望对您有所帮助