导出微信通讯录到 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

posted @ 2018-11-19 18:20  renyangli  阅读(4001)  评论(0编辑  收藏  举报