1. 程式人生 > >匯出微信通訊錄到 Excel

匯出微信通訊錄到 Excel

/**
 * 將 contacts 轉化成你需要的格式
 * 這裡可以任意發揮
 * @param contacts
 * @returns {*}
 */
function formatContacts(contacts) {
    return contacts.map(({NickName, Sex, RemarkName}) => {
        return {
            '暱稱': NickName,
            '備註': RemarkName
        }
    })
}

/**
 * 載入 script
 * @param url
 * @returns {Promise}
 */
function loadScript(url) {
    return new Promise((resolve) => {
        var head = document.getElementsByTagName('head')[0];
        var script = document.createElement('script');
        script.type = 'text/javascript';
        script.onload = resolve;
        script.src = url;
        head.appendChild(script);
    })

}

/**
 * 下載檔案
 * @param obj
 * @param fileName
 */
function saveAs(obj, fileName) {
    var a = document.createElement('a');
    a.download = fileName || '下載';
    a.href = URL.createObjectURL(obj);
    a.click(); // 模擬點選實現下載
    setTimeout(function () {
        URL.revokeObjectURL(obj); // 釋放 objectURL
    }, 100);
}

/**
 * 字串轉字元流
 * @param s
 * @returns {ArrayBuffer}
 */
function s2ab(s) {
    var buf = new ArrayBuffer(s.length);
    var view = new Uint8Array(buf);
    for (var i = 0; i !== s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
    return buf;
}

var scope = angular.element($('.scroll-wrapper .J_ContactScrollBody')).scope();
var allContacts = scope.allContacts;
// 過濾真實的使用者
var contacts = allContacts.filter(c => c.UserName);

// 下載 excel 指令碼
loadScript('https://oss.sheetjs.com/js-xlsx/xlsx.full.min.js')
    .then(() => {
        console.log('download js-xlsx successful ');

        var config = {bookType: 'xlsx', bookSST: false, type: 'binary'};//這裡的資料是用來定義匯出的格式型別
        var wb = {SheetNames: ['Sheet1'], Sheets: {}, Props: {}};
        // 通過json_to_sheet 轉成單頁(Sheet)資料
        wb.Sheets['Sheet1'] = XLSX.utils.json_to_sheet(formatContacts(contacts));
        var fileName = '微信通訊錄' + '.' + (config.bookType == "biff2" ? "xls" : config.bookType);
        saveAs(new Blob([s2ab(XLSX.write(wb, config))], {type: 'application/octet-stream'}), fileName);

    });

 摘自https://www.colabug.com/5256033.html

匯出微信通訊錄到 Excel