2

I try to import a CSV file via javascript. But the encoding is wrong. "ä, ö, ü, etc." are probably imported with ANSI instead of UTF-8.

The CSV file is exported before by me, there I managed to set the encoding to UTF-8. But I fail to import it correctly. Can anyone show me how this import should be done?

To illustrate the current problem:

Export format:

Männlich;Sehr geehrter;Per Sie;Dr.;Jürgen;Böhler;[email protected]

Import format:

Männlich;Sehr geehrter;Per Sie;Dr.;Jürgen;Böhler;[email protected]

Export function

function csv() {

        const rows = [[geschlecht[0].value, anrede[0].value, umgangsform[0].value, titel[0].value, vorname[0].value,nachname[0].value,email[0].value ]];
        var universalBOM = "\uFEFF";
        var csvContent = '';
        rows.forEach(function(rowArray){
            let row = rowArray.join(";");
            csvContent += row + "\r\n";
            for (i = 1; i < titel.length; i++) {

                csvContent +=  geschlecht[i].value + ';' + anrede[i].value + ';' + umgangsform[i].value + ';' + titel[i].value + ';' + vorname[i].value + ';' + nachname[i].value + ';' + email[i].value + "\r\n";
            }

        });
        var link = document.createElement("a");
        link.setAttribute("href", "data:text/csv;charset=utf-8," + encodeURIComponent(universalBOM+csvContent));
        link.setAttribute("download", "export.csv");
        document.body.appendChild(link); // Required for FF

        link.click(); // This will download the data file named "export.csv".

    }

Import function

function readBlob(opt_startByte, opt_stopByte) {

    var files = document.getElementById('files').files;
    if (!files.length || !((files[0].name).endsWith(".csv"))) {
      alert('Bitte eine .csv-Datei auswählen!');
      return;
    }

    var file = files[0];
    var start = parseInt(opt_startByte) || 0;
    var stop = parseInt(opt_stopByte) || file.size - 1;

    var reader = new FileReader();

    // If we use onloadend, we need to check the readyState.
    reader.onloadend = function(evt) {
    if (evt.target.readyState == FileReader.DONE) { // DONE == 2
       document.getElementById('textareaMails').value += evt.target.result;
      }
    };

    var blob = file.slice(start, stop + 1);
    reader.readAsBinaryString(blob);


  }

  document.querySelector('.readBytesButtons').addEventListener('click', function(evt) {

    if (evt.target.tagName.toLowerCase() == 'button') {
      var startByte = evt.target.getAttribute('data-startbyte');
      var endByte = evt.target.getAttribute('data-endbyte');
      readBlob(startByte, endByte);

    }
  }, false);
1

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.