Answer the question
In order to leave comments, you need to log in
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' );
Answer the question
In order to leave comments, you need to log in
Replace it
on this
saveAs( new Blob( rows, {type : 'text/csv;charset=utf-8'}), 'data.csv' );
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);
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question