티스토리 뷰

반응형
SMALL

Javascript 언어로 ANSI형식으로 저장된 csv파일을 불러오는 방법을 정리해보고자 한다.


csv파일의 경우 주로 엑셀 프로그램에서 저장하는 형식 중 하나인데 Microsoft Excel의 경우 인코딩 형식을 따로 설정한 후 저장할 수 있느 기능이 존재하여 ANSI 던지 UTF-8 이던지 결정할 수 있지만 한셀이나 넥셀같은 국산 소프트웨어의 경우 Excel처럼 사용자가 형식을 저장할 수 없이 ANSI 형식으로 저장된다.


ANSI 형식은 euc-kr형식이며 windows-1252형식과 동일하다.

이러한 형식으로 HTML5 FIleReader를 활용한 csv Reader를 구현해보고자 한다.


<html> <head> <script> // Check for the various File API support. if (window.File && window.FileReader && window.FileList && window.Blob) { // Great success! All the File APIs are supported. } else { alert('The File APIs are not fully supported in this browser.'); } </script> </head> <body> <input type="file" id="files" name="files[]" multiple /> <output id="list"></output> <table id="outputTable"> </table> <script> var table = document.getElementById('outputTable'); function parseCSV(text, lineTerminator, cellTerminator) { //break the lines apart var lines = text.split(lineTerminator); for(var j = 0; j<lines.length; j++){ if(lines[j] != ""){ //create a table row var tableRow = table.appendChild(document.createElement('tr')); //split the rows at the cellTerminator character var information = lines[j].split(cellTerminator); for(var k = 0; k < information.length; k++){ //append the cell to the row var cell = tableRow.appendChild(document.createElement('td')); cell.appendChild(document.createTextNode(information[k])); } } } } function handleFileSelect(evt) { var files = evt.target.files; // FileList object // Loop through the FileList and populate the 'outputTable' with the data for (var i = 0, f; f = files[i]; i++) { var reader = new FileReader(); // Closure to capture the file information. reader.onload = (function(theFile) { return function(e) { //call the parse function with the proper line terminator and cell terminator parseCSV(e.target.result, '\n', ';'); }; })(f); // Read the file as text reader.readAsText(f, "euc-kr"); } } document.getElementById('files').addEventListener('change', handleFileSelect, false); </script> </body> </html>


아래는 예시 CSV파일이다.

열1,열2,열3,열4
데이터1-1,데이터2-1,데이터3-1,데이터4-1
데이터1-2,데이터2-2,데이터3-2,데이터4-2
 


위 데이터를 바탕으로 실행한 결과를 스크린샷으로 첨부한다.


이상으로 ANSI (euc-kr / windows-1252) 형식으로 저장된 csv파일을 불러오는 방법을 정리해보았다.

반응형
LIST

'Frontend > Javascript' 카테고리의 다른 글

두 날짜 사이에 주말을 제외한 날짜 수 구하기  (3) 2017.12.02
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함