I want JavaScript to download CSV files from UTF-16

Asked 2 years ago, Updated 2 years ago, 145 views

I would like to download CSV using JavaScript.

"I would like to support ""UTF-16 BOM present"", but when I look at the file that I was able to support with the code below, the character code is hexedicimel, and the contents are 000. "
I want to know what's wrong.

function exportCSV(records){
   let data = records.map(record)=>record.join('\t')}).join('\r\n');
   csv_string="\ufeff"+data;//UTF-16

    var array=[];
    for(vari=0;i<csv_string.length;i++){
     array.push(csv_string.charCodeAt(i));
    }
   varcsv_contents = new Uint16 Array(array);

   var blob = new Blob([csv_contents], {
                                type: "text/csv; charset=utf-16;"
   });
   let url=(window.URL||window.webkitURL).createObjectURL(blob);
   let link = document.createElement('a');
   link.download = 'result.csv';
   link.href=url;
   document.body.appendChild(link);
   link.click();
   document.body.removeChild(link);
};

javascript csv character-code

2022-09-30 20:21

1 Answers

When I saved and executed the following code in UTF-8 in my environment, I was able to output the TSV file as UTF-16LE BOM successfully.

The code you asked seems to be different from the original code, such as record.join('\t')} with } and cannot be executed, so it may be caused by rewriting and shaving the sample code.

Could you edit the questionnaire so that it has a short reproducible sample code that works alone with data?

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Sample</title>
</head>
<body>
<script>
function exportCSV(records){
   let data = records.map(record)=>record.join('\t')).join('\r\n');
   csv_string="\ufeff"+data;//UTF-16

    var array=[];
    for(vari=0;i<csv_string.length;i++){
     console.log(csv_string[i]);
     array.push(csv_string.charCodeAt(i));
    }
   varcsv_contents = new Uint16 Array(array);

   var blob = new Blob([csv_contents], {
                                type: "text/csv; charset=utf-16;" 
   });
   let url=(window.URL||window.webkitURL).createObjectURL(blob);
   let link = document.createElement('a');
   link.download = 'result.csv';
   link.href=url;
   document.body.appendChild(link);
   link.click();
   document.body.removeChild(link);
};

rs = [["a", "b", "c"],
      ["A", "B", "C"],
      ["i", "ro", "ha"];
exportCSV(rs);
</script>
</body>
</html>


2022-09-30 20:21

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.