CSV для пользовательского пользовательского отчета (Dygraph) - PullRequest
1 голос
/ 17 марта 2020

Я пытаюсь создать красивый отчет на основе данных, которые я получаю от Codesys PL C. Я собираюсь создать страницу HTML, где вы можете поместить файл с данными, а затем он будет проанализирован в указанных полях c.

Codesys PL C записывает файл CSV следующего формата :

  • в разделе некоторые общие данные процесса
  • при тенденциях, которые я собираюсь визуализировать с помощью Dygraph.

Я тестировал Dygraph, когда файл CSV состоит из только с данными GRAPH (начинается непосредственно со строки подписей). Я создал новый граф и передал ему файл CSV в виде файла от FileReader.

Теперь я пытаюсь справиться с разделом. Я могу читать его построчно, но затем мне нужно снова обработать раздел как File, чтобы поместить его в Dygraph.

Итак, главный вопрос , как прочитать файл как файл CSV из спецификации c position?

Я протестировал некоторый код, который я собираю из нескольких примеров. Я прошу прощения за это, я знаю, что это не хорошо, но я новичок в jscript и веб-программировании.

Но это работает для отображения графика.

CSV-файл:

ОТЧЕТ StartDate, 2020/02/05 12:26:53 EndDateDate, 2020/02/06 12:26:53 Статус, Закончено Средняя температура, 123,45 Среднее давление, 0,0567

ГРАФ Время, температура, давление 2020/02/05 12: 26: 53,54.53312,0.5453312 2020/02/05 12: 26: 55,40.7445,0.1613245 2020/02/05 12: 26: 56,7.167816,0.03520107 2020/02/05 12: 26: 57,78.76286,0.03732681 2020/02/05 12: 26: 58,22.20001,0.06941796 2020/02/05 12: 27: 00,34.79605,0.7027158

<div id="graph"></div>
<input type="file" id="files" name="files[]" multiple />
<output id="list"></output>

<table id="outputTable">    
</table>

<script>

  var table = document.getElementById('outputTable');

  function parseCSV(text, lineTerminator, cellTerminator) {

g = new Dygraph(
document.getElementById("graph"),
text,
{
        series: {
          'temperature': {
            axis: 'y'
          },
          'pressure': {
            axis: 'y2'
          },
        },
        axes: {
          y: {
            labelsKMB: true,
            independentTicks: true
          },
          y2: {
            // set axis-related properties here
            labelsKMB: true,
            independentTicks: true
          }
        },
        ylabel: 'Primary y-axis',
        y2label: 'Secondary y-axis',

});


    //break the lines apart
    var lines = text.split(lineTerminator);

    for(var j = 0; j<lines.length; j++){

        if(lines[j] != ""){

            //create a table row 
            var tableRow = table.appendChild(document.createElement('tr'));

            //split the rows at the cellTerminator character
            var information = lines[j].split(cellTerminator);

            for(var k = 0; k < information.length; k++){
                //append the cell to the row
                var cell = tableRow.appendChild(document.createElement('td'));
                cell.appendChild(document.createTextNode(information[k]));

            }

        }

    }

  }

  function handleFileSelect(evt) {
    var files = evt.target.files; // FileList object

    // Loop through the FileList and populate the 'outputTable' with the data
    for (var i = 0, f; f = files[i]; i++) {

      var reader = new FileReader();



      // Closure to capture the file information.
      reader.onload = (function(theFile) {
        return function(e) {

          //call the parse function with the proper line terminator and cell terminator
          parseCSV(e.target.result, '\n', ';');

        };
      })(f);

      // Read the file as text
      reader.readAsText(f);

    }
  }

  document.getElementById('files').addEventListener('change', handleFileSelect, false);
</script>
...