2015年1月13日 星期二

【Javascript】匯出 csv

將 table 的內容匯出成 csv 檔案
利用 encodeURIComponent
將字串轉為 Data URI
但要注意轉出的 code 為 UTF-8 編碼
若直接用 Microsoft Office Excel 開啟 csv 檔案時
中文會變成亂碼
因為 Excel 無法預設讀取 UTF-8 編碼的 CSV 檔案
所以利用增加 UTF-8 BOM 的方式
讓 Excel 直接開啟 csv 不會出現亂碼
navigator.appVersion.indexOf("Win") 若回傳值不為 -1
表示 OS 為 Windows 系列
指定 charset 為 帶 BOM 的 UTF-8

產生 CSV 內容的資料處理部分
傳入的參數 _csvString
除了每列資料要加斷行符號
不同欄位之間的資料要加逗號之外
還要額外處理兩個地方
1.資料若含有特殊符號,例如逗號,資料需加上雙引號
2.資料內容若已有雙引號,建議用 replace 取代為兩個雙引號
這樣用 Excel 開啟時,瀏覽效果較佳
function exportToCSV( _csvString ) {
    var downloadLink = document.createElement("a");
    downloadLink.download = "dataTable.csv";
    downloadLink.innerHTML = "Download File";
    if (window.webkitURL != null) {
        var code = encodeURIComponent( _csvString );
        if ( navigator.appVersion.indexOf("Win")==-1 ) {
            downloadLink.href = "data:application/csv;charset=utf-8," + code;
        } else {
            downloadLink.href = "data:application/csv;charset=utf-8,%EF%BB%BF" + code;
        }
    }

    downloadLink.click();
}

2015年1月8日 星期四

【Javascript】匯出txt


因為有將 Log 直接寫進 html 裡面
所以就想說將網頁上的純文字內容輸出為一個 txt 檔案
saveTextAsFile function 內有兩個參數
第一個參數 _fileName 為預設在本地端存檔的檔名
第二個參數 _text 為輸出的純文字內容

function saveTextAsFile( _fileName, _text ) {
    var textFileAsBlob = new Blob([_text], {type:'text/plain'});

    var downloadLink = document.createElement("a");
    downloadLink.download = _fileName;
    downloadLink.innerHTML = "Download File";
    if (window.webkitURL != null) {
        // Chrome allows the link to be clicked
        // without actually adding it to the DOM.
        downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
    } else {
        // Firefox requires the link to be added to the DOM
        // before it can be clicked.
        downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
        downloadLink.onclick = destroyClickedElement;
        downloadLink.style.display = "none";
        document.body.appendChild(downloadLink);
    }

    downloadLink.click();
}

function destroyClickedElement(event) {
    document.body.removeChild(event.target);
}