Search code examples
htmlunicode

How to read a CSV file with hindi character and display on html?


Html is display text like this. I already checked and meta charset is already utf-8. I don't know why is happening Please help :)

id,cityname,{{man1}},{{number1}},{{man2}},{{number2}},{{man3}},{{number3}},{{man4}},{{number4}}
78,à¤à¤¯à¤¾,vikasasash,1212121212,vikashas,N/A,vikassash,N/A,vikash,1212121212 77,पà¤à¤¨à¤¾,पà¤à¤¨à¤¾,1212121212,पà¤à¤¨à¤¾,9601860927,पà¤à¤¨à¤¾,1212121212,vikash,1212121212
89,ठाणà¥,vikashas,1212121212,vikashas,N/A,vikash,1212121212,vikash,1212121212
87,पà¥à¤£à¥,vikashअयोध्या,N/A,vikash,N/A,vikash,N/A,vikash,N/A we are saved

I was reading the file like this and display it on the screen. Since meta is utf-8. it should display them correct but it is noot

      var readCSV = new FileReader();
      readCSV.readAsBinaryString(file);
      readCSV.onloadend = function () {

        //arrayofArray converting them into 2D 
        const arrayofArrays = convertCSVToArray(readCSV.result, {
          type: 'array',
          separator: ','
        });

Solution

  • Here's a basic example of how to parse the CSV with javascript.

    I got no errors because of the hindi characters. Note that all values are strings and you still need to convert some values to numbers and handle the {{man1}} double brackets stuff.

    const inputElement = document.getElementById("csv");
    
    inputElement.addEventListener("change", handleFile);
    
    function handleFile () {
      let file = this.files[0];
      let fileReader = new FileReader();
      fileReader.onload = handleText;
      fileReader.readAsText(file);
    }
    
    function handleText () {
      let lines = this.result.split('\n');
      let headers = lines[0].split(',');
      let parsed = [];
      for (let i=1; i<lines.length; i++) {
        let line = lines[i].split(',');
        let item = {};
        for (let j=0; j<headers.length; j++) {
          item[headers[j]] = line[j];
        }
        parsed.push(item);
      }
      console.log(parsed);
    }
    <input type="file" id="csv" accept="text/csv">