S
S
Sergey Sokolov2017-04-20 21:31:26
JavaScript
Sergey Sokolov, 2017-04-20 21:31:26

How to generate a CSV file for MS Excel from JS?

How to generate a CSV file that will open normally in Excel? JS tools.
I care about the Cyrillic text encoding and the column separator , which, as I understand it, each one sets according to his mood (regional settings) in Windows.
To save a file directly from the page, I use FileSaver.js .
For example, there is data in two columns:

var data = [
  [123,"первая строка вторая колонка в кириллице"],
  [456,"вторая строка"]
];
data = data.map(function(el){ return [el[0], '"' + el[1] + '"'].join(',') + "\r\n"; });
saveAs( new Blob( data, {type : 'text/csv'}), 'data.csv' );

Fiddle - when you click on the button, it will offer to save the CSV file - it opens normally in Google Spreadsheets and Preview on Mac OS X sees it as a normal table:
195df0f5c6df41daac231ea03db03037.png
And on Windows, Excel opens in one column with a broken encoding:
9cb53a9b716f4d22a2e581a586d1578e.jpg
How to generate data for visitors under Windows?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
Y
Yakov Vylegzhanin, 2017-04-21
@vylegzhanin

Replace it
on this

saveAs( new Blob( rows, {type : 'text/csv;charset=utf-8'}), 'data.csv' );

S
SunSpire, 2020-11-26
@SunSpire

To get rid of "broken" characters in the saved CSV file, you should manually recode the Cyrillic alphabet and save the original data into a binary array. Here is the JS function I use to generate CSV lab reports:

// перехватываем событие message и вызываем нужную нам функцию
(function(p) {
    window.alert = function() {
        sData = arguments[0];       
        download(sData) 
    };
})(window.alert);

// функция скачивания файла на жесткий диск
function download(data) {                
         
         // делаем перекодировку кириллических символов
         var uint8 = new Uint8Array(data.length);
         for(var i = 0; i < data.length; i++) {
             x = data.charCodeAt(i);
             if (x >= 1040 && x <= 1103) { // Символы А..Я а..я
                 x -= 848;
             } else if (x == 1025) {   // Символ Ё
                 x = 168;
             } else if (x == 1105) {   // Символ ё
                 x = 184;
             }
             uint8[i] = x;
         }

         // имя сохраняемого файла
         filename = "lab_report.csv"     
    
         // сохраняем файл (в качестве данных - массив)
         var file = new Blob([uint8], {type: 'text/csv'});    

         if (window.navigator.msSaveOrOpenBlob) // IE10+
             window.navigator.msSaveOrOpenBlob(file, filename);
         else { // Others
             var a = document.createElement("a"),
                     url = URL.createObjectURL(file);
             a.href = url;
             a.download = filename;
             document.body.appendChild(a);
             a.click();
             setTimeout(function() {
                 document.body.removeChild(a);
                 window.URL.revokeObjectURL(url);  
         }, 0); 
    }
}

D
Dark Hole, 2017-04-20
@abyrkov

Try this converter - stackoverflow.com/questions/2696481/encoding-conve...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question