js-> excel

const tableToExcel = () => {
    // 要导出的json数据
    const jsonData = [
        {
            name:'路人甲1',
            phone:'123456',
            email:'[email protected]'
        },
        {
            name:'炮灰乙',
            phone:'123456',
            email:'[email protected]'
        },
        {
            name:'土匪丙',
            phone:'123456',
            email:'[email protected]'
        },
        {
            name:'流氓丁1',
            phone:'123456',
            email:'[email protected]'
        },
    ]
    // 列标题
    let str = '姓名电话邮箱';
    // 循环遍历,每行加入tr标签,每个单元格加td标签
    for(let i = 0 ; i < jsonData.length ; i++ ){
        str+='';
        for(const key in jsonData[i]){
            // 增加\t为了不让表格显示科学计数法或者其他格式
            str+=`${ jsonData[i][key] + '\t'}`;     
        }
        str+='';
    }
    // Worksheet名
    const worksheet = 'Sheet1'

    
    // const uri = 'data:application/vnd.ms-excel;base64,'; // xls
    const uri = 'data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,'; // xlsx
    

    // 下载的表格模板数据
    const template = `
    
    ${str}
`; // 下载模板 // window.location.href = uri + window.btoa(unescape(encodeURIComponent(template))); const link = document.createElement('a') link.href = uri + window.btoa(unescape(encodeURIComponent(template))); link.download = '123.xlsx' // 对下载的文件命名 link.click() };
export default {
  exportExcel: (columns = [], list = [], fileName = '下载', fileType = 'xls', sheetName = 'Sheet1') => {

    let str = ''
    if (columns.length) {
      str += ''
      columns.forEach(column => {
        str += '' + column['cnName'] + ''
      });
      str += '';
    }

    list.forEach((row) => {
      str += '';
      columns.forEach(column => {
        str += `${row[column['enName']] + '\t'}`;
      })
      str += '';
    })

    let uri = '';
    if (fileType === 'xlsx') {
      uri = 'data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,'; // xlsx
    } else {
      uri = 'data:application/vnd.ms-excel;base64,' // xls
    }

    // 下载的表格模板数据
    let template = '';
    template += ''
    template += ' '
    template += '  '
    template += ' '
    template += ' '
    template += ''
    template += ' ' + str + '
' template += '' template += '' // 下载模板 // window.location.href = uri + window.btoa(unescape(encodeURIComponent(template))); const link = document.createElement('a') link.href = uri + window.btoa(unescape(encodeURIComponent(template))); link.download = fileName + '.' + fileType // 对下载的文件命名 例如 123.xls link.click() } } // 调用 let columns = [ {'enName': 'name', 'cnName': '姓名'}, {'enName': 'age', 'cnName': '年龄'}, ] let list = [ {name: '张三张三张三张三张三', age: 30}, {name: '李四', age: 40}, ]; xysExcel.exportExcel(columns, list)

你可能感兴趣的:(js-> excel)