Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[20210318] JS - str to 2D array, SheetJS, splice() #71

Open
JuHyun419 opened this issue Mar 18, 2021 · 0 comments
Open

[20210318] JS - str to 2D array, SheetJS, splice() #71

JuHyun419 opened this issue Mar 18, 2021 · 0 comments

Comments

@JuHyun419
Copy link
Owner

JuHyun419 commented Mar 18, 2021

JavaScript 2차원 배열 형식의 문자열을 2차원 배열로 변환하기

  • 필요없는 문자 제거 => "[ ] 공백"
  • split => String to Array
  • splice() => 1D Array to 2D Array
    • 배열 요소 추가 및 삭제
// String
var datas = "[[고객코드, 매장코드, 고객 전화번호], [0, AAAA, 01011112222], [1, AAAA, 01011112222], [2, ABCD, 01011112222], [3, AAAA, 01022223333], [4, BBBB, 01022223333]]";


// 2차원 배열(Object)
var array = arrayTo2DArray(strToArray(excelDatas), 3);

// 문자열 to 1차원 array
function strToArray(str) {
    str = str.replace(/[\[\]']+/g, '');
    var array = [];
    
    array = str.split(',');
    	
    for (var i = 0; i < array.length; i++) {
    	array[i] = array[i].trim();
    }
    	
    return array;
}
    
// 1차원 array to 2차원 array
function arrayTo2DArray(array, count) {
    newArray = [];
    	
    while (array.length > 0) {
    	newArray.push(array.splice(0, count));
    }
    	
    return newArray;
}

SheetJS

  • JS에서 엑셀 Read 및 Write 하는 매우 간단하고 편리한 오픈소스
<!-- 필수, SheetJS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.14.3/xlsx.full.min.js"></script>
<!--필수, FileSaver savaAs 이용 -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.8/FileSaver.min.js"></script>

...

    // Excel write
    function exportExcel(){ 
        var workbook = XLSX.utils.book_new();
        workbook.SheetNames.push("sheet1");

        // array => 위 설명에 있는 2차원 배열, 엑셀 sheet에 write할 데이터
        var wsData = this.array;

        // aoa => array of array, Json 등 다른 방식도 가능
        var worksheet = XLSX.utils.aoa_to_sheet(wsData);
        
        // 시트 데이터를 시트에 넣기 (시트 명이 없는 시트인경우 첫번째 시트에 데이터가 들어감 )
        workbook.Sheets["sheet1"] = worksheet;

        // 엑셀 파일 쓰기
        var exportWorkbook = XLSX.write(workbook, {bookType:'xlsx',  type: 'binary'});

        // 파일 다운로드
        saveAs(new Blob([s2ab(exportWorkbook)], {type:"application/octet-stream"}), excelFileName);
    }

    function s2ab(datas) { 
        var buf = new ArrayBuffer(datas.length); 
        var view = new Uint8Array(buf);  //create uint8array as viewer
        for (var i=0; i<datas.length; i++) view[i] = datas.charCodeAt(i) & 0xFF; //convert to octet
        return buf;    
    }

References

https://github.com/SheetJS
https://redstapler.co/sheetjs-tutorial-create-xlsx/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant