programing tip

서버 상호 작용없이 자바 스크립트 데이터를 CSV 파일로 내보내기

itbloger 2020. 10. 18. 08:40
반응형

서버 상호 작용없이 자바 스크립트 데이터를 CSV 파일로 내보내기


nodeJS 서버에 있다면 헤더를 작성하고 MIME 유형을 설정하여 전송할 수 있습니다.

res.header("Content-Disposition", "attachment;filename="+name+".csv"); 
res.type("text/csv");
res.send(200, csvString);

헤더로 인해 브라우저는 명명 된 csv 파일에 대한 다운로드를 생성합니다.

브라우저에서 유용한 데이터가 생성 될 때 CSV 파일로 가져 오는 한 가지 해결책은 ajax를 사용하여 서버에 업로드하고 (아마도 여기에 저장) 서버가 이러한 헤더와 함께 데이터를 다시 보내도록하는 것입니다. csv는 브라우저에서 다시 다운로드합니다.

그러나 서버와 핑퐁을 사용하지 않는 100 % 브라우저 솔루션을 원합니다.

그래서 새 창을 열고 META 태그에 상응하는 헤더를 설정할 수 있다는 생각이 들었습니다.

그러나 이것은 최근 Chrome에서 작동하지 않습니다.

새 창이 표시되고 csvString이 포함되어 있지만 다운로드로 작동하지 않습니다.

나는 하단 탭에 다운로드를 받거나 하단 탭에 다운로드가있는 빈 새 창을 얻을 것으로 예상했다.

메타 태그가 올바른지 또는 다른 태그도 필요한지 궁금합니다.

서버에 펀팅하지 않고이 작업을 수행 할 수있는 방법이 있습니까?

브라우저에서 CSV 생성을위한 JsFiddle (작동하지 않음-출력 창이지만 다운로드 없음)

var A = [['n','sqrt(n)']];  // initialize array of rows with header row as 1st item
for(var j=1;j<10;++j){ A.push([j, Math.sqrt(j)]) }
var csvRows = [];
for(var i=0,l=A.length; i<l; ++i){
    csvRows.push(A[i].join(','));   // unquoted CSV row
}
var csvString = csvRows.join("\n");
console.log(csvString);
var csvWin = window.open("","","");
csvWin.document.write('<meta name="content-type" content="text/csv">');
csvWin.document.write('<meta name="content-disposition" content="attachment;  filename=data.csv">  ');
csvWin.document.write(csvString);

항상 HTML5 download속성이 있습니다.

이 속성 (있는 경우)은 작성자가 리소스를 다운로드하는 데 하이퍼 링크를 사용하도록 의도했음을 나타내므로 사용자가 링크를 클릭하면 로컬 파일로 저장하라는 메시지가 표시됩니다.

속성에 값이있는 경우 사용자가 링크를 클릭하면 열리는 저장 프롬프트에서 값이 미리 채워진 파일 이름으로 사용됩니다.

var A = [['n','sqrt(n)']];

for(var j=1; j<10; ++j){ 
    A.push([j, Math.sqrt(j)]);
}

var csvRows = [];

for(var i=0, l=A.length; i<l; ++i){
    csvRows.push(A[i].join(','));
}

var csvString = csvRows.join("%0A");
var a         = document.createElement('a');
a.href        = 'data:attachment/csv,' +  encodeURIComponent(csvString);
a.target      = '_blank';
a.download    = 'myFile.csv';

document.body.appendChild(a);
a.click();

깡깡이

Chrome 및 Firefox에서 테스트되었으며 최신 버전에서 정상적으로 작동합니다 (2013 년 7 월 기준) .
Opera에서도 작동하지만 파일 이름은 설정하지 않습니다 (2013 년 7 월 기준) .
IE9 (큰 놀라움)에서 작동하지 않는 것 같습니다 (2013 년 7 월 현재) .

다운로드 속성을 지원하는 브라우저에 대한 개요는 여기 에서 찾을 수 있습니다.
지원되지 않는 브라우저의 경우 서버 측에 적절한 헤더를 설정해야합니다.


분명히 속성을 지원하지 않는 IE10 및 IE11 해킹이 있습니다 (Edge는 지원합니다 ) .download

var A = [['n','sqrt(n)']];

for(var j=1; j<10; ++j){ 
    A.push([j, Math.sqrt(j)]);
}

var csvRows = [];

for(var i=0, l=A.length; i<l; ++i){
    csvRows.push(A[i].join(','));
}

var csvString = csvRows.join("%0A");

if (window.navigator.msSaveOrOpenBlob) {
    var blob = new Blob([csvString]);
    window.navigator.msSaveOrOpenBlob(blob, 'myFile.csv');
} else {
    var a         = document.createElement('a');
    a.href        = 'data:attachment/csv,' +  encodeURIComponent(csvString);
    a.target      = '_blank';
    a.download    = 'myFile.csv';
    document.body.appendChild(a);
    a.click();
}

@adeneo 답변은 Firefox 및 chrome에서 작동합니다 ... IE의 경우 아래를 사용할 수 있습니다.

if (window.navigator.msSaveOrOpenBlob) {
  var blob = new Blob([decodeURIComponent(encodeURI(result.data))], {
    type: "text/csv;charset=utf-8;"
  });
  navigator.msSaveBlob(blob, 'FileName.csv');
}


adeneo의 답변을 참조하십시오.하지만 잊지 마세요 encodeURIComponent!

a.href     = 'data:application/csv;charset=utf-8,' + encodeURIComponent(csvString);

Also, I needed to do "\r\n" not just "\n" for the row delimiter.

var csvString = csvRows.join("\r\n");

Revised fiddle: http://jsfiddle.net/7Q3c6/


Once I packed JS code doing that to a tiny library:

https://github.com/AlexLibs/client-side-csv-generator

The Code, Documentation and Demo/Playground are provided on Github.

Enjoy :)

Pull requests are welcome.


See adeneo's answer, but to make this work in Excel in all countries you should add "SEP=," to the first line of the file. This will set the standard separator in Excel and will not show up in the actual document

var csvString = "SEP=, \n" + csvRows.join("\r\n");

We can easily create and export/download the excel file with any separator (in this answer I am using the comma separator) using javascript. I am not using any external package for creating the excel file.

    var Head = [[
        'Heading 1',
        'Heading 2', 
        'Heading 3', 
        'Heading 4'
    ]];

    var row = [
       {key1:1,key2:2, key3:3, key4:4},
       {key1:2,key2:5, key3:6, key4:7},
       {key1:3,key2:2, key3:3, key4:4},
       {key1:4,key2:2, key3:3, key4:4},
       {key1:5,key2:2, key3:3, key4:4}
    ];

for (var item = 0; item < row.length; ++item) {
       Head.push([
          row[item].key1,
          row[item].key2,
          row[item].key3,
          row[item].key4
       ]);
}

var csvRows = [];
for (var cell = 0; cell < Head.length; ++cell) {
       csvRows.push(Head[cell].join(','));
}
            
var csvString = csvRows.join("\n");
let csvFile = new Blob([csvString], { type: "text/csv" });
let downloadLink = document.createElement("a");
downloadLink.download = 'MYCSVFILE.csv';
downloadLink.href = window.URL.createObjectURL(csvFile);
downloadLink.style.display = "none";
document.body.appendChild(downloadLink);
downloadLink.click();

참고URL : https://stackoverflow.com/questions/17836273/export-javascript-data-to-csv-file-without-server-interaction

반응형