簡體   English   中英

如何在我的網站上使用我的 CSV 文件中的數據?

[英]How do i use the data in my CSV file on my website?

我正在嘗試從 CSV 文件中獲取數據以將其顯示到我的網站,方法是使用兩個值作為 x 和 y 坐標,就像在圖表上一樣,並在該位置獲取數據。

這是我的 HTML 代碼

<form>
    Width <input type="text" id="W">
    Height <input type="text" id="H">
    Length <input type="text" id="L">
    <button type="button" onclick="f()">Calculate</button>
    <b id="result"></b>
</form>

這是我的 CSS 代碼

function f()
{

    var L = parseInt(document.querySelector("#L").value);
    var W = parseInt(document.querySelector("#W").value);
    var H = parseInt(document.querySelector("#H").value);

    var A;
    var B;
    var calc;

    // These are the X and Y values that i want to use
    A = 2*(H+2)+W+5;
    B = 2*(H+2)+L+5;

    //calc = this the variable where I would like to store the data from the CSV file

    document.querySelector("#result").innerHTML = calc;
}

我擁有的數據的一個例子是這樣的

   0 1 2 3 4 5 6 7 8 
   | | | | | | | | |
0--1 2 3 4 5 6 7 8 9 
1--2 3 4 5 6 7 8 9 1
2--3 4 5 6 7 8 9 1 2
3--4 5 6 7 8 9 1 2 3
4--5 6 7 8 9 1 2 3 4
5--6 7 8 9 1 2 3 4 5
6--7 8 9 1 2 3 4 5 6
7--8 9 1 2 3 4 5 6 7
8--9 1 2 3 4 5 6 7 8

基本上我想要做的是將 CSV 數據加載到類似數組的二維數組中,然后使用 A 和 B 值獲取存儲在那里的任何內容。

您需要使用 XMLHttpRequest aka AJAX 或 File Blob 加載 csv 文件,然后您需要在進行任何計算之前對其進行解析。 這是很多工作。

希望一些傑出的人研究了一個您可以重復使用的解決方案。 https://www.papaparse.com 在這里你可以找到如何安裝這個庫: https://github.com/mholt/PapaParse#install

如果您不想在某處托管文件並使用 AJAX 加載它,那么您可以添加文件輸入並手動提交文件,PapaParse 可以使用 File Blob。

添加到您的 html 新輸入:

<input type="file"
       id="csvFile"
       accept="text/csv">

然后添加到您的 Javascript:

const fileInput = document.querySelector('#csvFile')

fileInput.addEventListener('change', () => {
  Papa.parse(fileInput.files[0], {
    complete: function(results) {
      console.log(results);

      // Here you can go through results and do your calculation
    }
  });
})

最簡單的方法是將 csv 粘貼到多行字符串中,然后從那里解決。

不推薦用於大型 csv。

function getByXY(x, y) {
//paste your csv in backticks not quotes 
    var data = `1 2 3 4 5 6 7 8 9 
    1 2 3 4 5 6 7 8 9 
    1 2 3 4 5 6 7 8 9`;

//Split by new line to get row
    let rows = a.split("\n");
// check your delimiter can value  can be separated by comma or space  
    let cols = rows[x].split(",");
  // take it out  
   let value = cols[y];
  // throw it back to caller
  return value;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM