【图片和表格数据导出excel】js把表格导出成excel格式,表格内的图片一起导出

效果图

在这里插入图片描述

代码

1,js代码,把这个代码复制到一个js文件内
表格样式可以在这里面调整,就是直接加在表格的标签上写样式,tr td 之类的

/* eslint-disable */
let idTmr;
const getExplorer = () => {
  let explorer = window.navigator.userAgent;
  //ie
  if (explorer.indexOf("MSIE") >= 0) {
    return 'ie';
  }
  //firefox
 
  else if (explorer.indexOf("Firefox") >= 0) {
    return 'Firefox';
  }
  //Chrome
  else if (explorer.indexOf("Chrome") >= 0) {
    return 'Chrome';
  }
  //Opera
  else if (explorer.indexOf("Opera") >= 0) {
    return 'Opera';
  }
  //Safari
  else if (explorer.indexOf("Safari") >= 0) {
    return 'Safari';
  }
}
// 判断浏览器是否为IE
const exportToExcel = (data,name) => {
 
  // 判断是否为IE
  if (getExplorer() == 'ie') {
    tableToIE(data, name)
  } else {
    tableToNotIE(data,name)
  }
}
 
const Cleanup = () => {
  window.clearInterval(idTmr);
}
 
// ie浏览器下执行
const tableToIE = (data, name) => {
  let curTbl = data;
  let oXL = new ActiveXObject("Excel.Application");
 
  //创建AX对象excel
  let oWB = oXL.Workbooks.Add();
  //获取workbook对象
  let xlsheet = oWB.Worksheets(1);
  //激活当前sheet
  let sel = document.body.createTextRange();
  sel.moveToElementText(curTbl);
  //把表格中的内容移到TextRange中
  sel.select;
  //全选TextRange中内容
  sel.execCommand("Copy");
  //复制TextRange中内容
  xlsheet.Paste();
  //粘贴到活动的EXCEL中
 
  oXL.Visible = true;
  //设置excel可见属性
 
  try {
    let fname = oXL.Application.GetSaveAsFilename("Excel.xls", "Excel Spreadsheets (*.xls), *.xls");
  } catch (e) {
    print("Nested catch caught " + e);
  } finally {
    oWB.SaveAs(fname);
 
    oWB.Close(savechanges = false);
    //xls.visible = false;
    oXL.Quit();
    oXL = null;
    // 结束excel进程,退出完成
    window.setInterval("Cleanup();", 1);
    idTmr = window.setInterval("Cleanup();", 1);
  }
}
 
// 非ie浏览器下执行
const tableToNotIE = (function() {
  // 编码要用utf-8不然默认gbk会出现中文乱码
  let uri = 'data:application/vnd.ms-excel;base64,',
    template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><meta charset="UTF-8"><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>',
    base64 = function(s) {
      return window.btoa(unescape(encodeURIComponent(s)));
 
    },
 
    format = (s, c) => {
      return s.replace(/{(\w+)}/g,
        (m, p) => {
          return c[p];
        })
    }
  return (table, name) => {
    let ctx = {
      worksheet: name,
      table
    }
 
    //创建下载
    let link = document.createElement('a');
    link.setAttribute('href', uri + base64(format(template, ctx)));
 
    link.setAttribute('download', name);
 
 
    // window.location.href = uri + base64(format(template, ctx))
    link.click();
  }
})()
 
// 导出函数
const export2Excel = (theadData, tbodyData, dataname) => {
 
  let re = /http/ // 字符串中包含http,则默认为图片地址
  let th_len = theadData.length // 表头的长度
  let tb_len = tbodyData.length // 记录条数
  let width = 120 // 设置图片大小
  let height = 120
 
  // 添加表头信息
  let thead = '<thead><tr style="width:' + 200 + 'px;height:' + 50 + 'px;">'
  for (let i = 0; i < th_len; i++) {
    thead += '<th>' + theadData[i] + '</th>'
  }
  thead += '</tr></thead>'
 
  // 添加每一行数据
  let tbody = '<tbody>'
  for (let i = 0; i < tb_len; i++) {
    tbody += '<tr>'
    let row = tbodyData[i] // 获取每一行数据
 
    for (let key in row) {
      if (re.test(row[key])) { // 如果为图片,则需要加div包住图片
        // 
        tbody += '<td style="width:' + width + 'px; height:' + height + 'px; text-align: center; vertical-align: middle"><div style="display:inline"><img src=\'' + row[key] + '\' ' + ' ' + 'width=' + '\"' + width + '\"' + ' ' + 'height=' + '\"' + height + '\"' + '></div></td>'
      } else {
        tbody += '<td style="text-align:center">' + row[key] + '</td>'
      }
    }
    tbody += '</tr>'
  }
  tbody += '</tbody>'
 
  let table = thead + tbody
 
  // 导出表格
  exportToExcel(table, dataname)
}

2,使用方法,组好表头和内容就行,图片会自动识别的。

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <!-- 公共css文件 -->
    <link rel="stylesheet" href="/statics/css/common/common.css">
    <!-- 公共js文件 -->
    <script type="text/javascript" src="/statics/vue_element/common.js"></script>
    <!-- vue方面文件 -->
    <link rel="stylesheet" href="/statics/vue_element/element.css">
    <script src="/statics/vue_element/vue.js"></script>
    <script src="/statics/vue_element/element.js"></script>
    <script src="/statics/vue_element/axios.js"></script>
    <!-- 引入excel导出组件 -->
    <script src="./qdcs.js"></script>
    <title>测试</title>
</head>

<body>
    <div id="app">
        <div @click="ceshi">
            导出测试
        </div>
    </div>
</body>
<script>
    new Vue({
        el: '#app',
        data() {
            return {
                tHeader: [
                    '科室',
                    '部门',
                    '照片'
                ],
                tbody: [
                    {
                        name: '科室1',
                        color: '部门1',
                        img: 'https://nimg.ws.126.net/?url=http%3A%2F%2Fdingyue.ws.126.net%2F2024%2F0510%2F11290a01j00sd90qe001dd000hs00hsg.jpg&thumbnail=660x2147483647&quality=80&type=jpg'
                    },
                    {
                        name: '科室12',
                        color: '部门2',
                        img: 'https://nimg.ws.126.net/?url=http%3A%2F%2Fdingyue.ws.126.net%2F2024%2F0510%2F11290a01j00sd90qe001dd000hs00hsg.jpg&thumbnail=660x2147483647&quality=80&type=jpg'
                    },
                    {
                        name: '科室13',
                        color: '部门3',
                        img: 'https://nimg.ws.126.net/?url=http%3A%2F%2Fdingyue.ws.126.net%2F2024%2F0510%2F11290a01j00sd90qe001dd000hs00hsg.jpg&thumbnail=660x2147483647&quality=80&type=jpg'
                    },
                    {
                        name: '科室14',
                        color: '部门4',
                        img: 'https://nimg.ws.126.net/?url=http%3A%2F%2Fdingyue.ws.126.net%2F2024%2F0510%2F11290a01j00sd90qe001dd000hs00hsg.jpg&thumbnail=660x2147483647&quality=80&type=jpg'
                    },
                    {
                        name: '科室15',
                        color: '部门5',
                        imgs: 'https://nimg.ws.126.net/?url=http%3A%2F%2Fdingyue.ws.126.net%2F2024%2F0510%2F11290a01j00sd90qe001dd000hs00hsg.jpg&thumbnail=660x2147483647&quality=80&type=jpg'
                    }
                ]
            }
        },
        methods: {
            ceshi(){
                export2Excel(this.tHeader, this.tbody, '我爱花朵')
            }
        }
    })
</script>

</html>

第二种写法(根据表头的key找表体内的内容一一对应)

js文件的内容

/* eslint-disable */
let idTmr;
const getExplorer = () => {
    let explorer = window.navigator.userAgent;
    //ie
    if (explorer.indexOf("MSIE") >= 0) {
        return 'ie';
    }
    //firefox

    else if (explorer.indexOf("Firefox") >= 0) {
        return 'Firefox';
    }
    //Chrome
    else if (explorer.indexOf("Chrome") >= 0) {
        return 'Chrome';
    }
    //Opera
    else if (explorer.indexOf("Opera") >= 0) {
        return 'Opera';
    }
    //Safari
    else if (explorer.indexOf("Safari") >= 0) {
        return 'Safari';
    }
}
// 判断浏览器是否为IE
const exportToExcel = (data, name) => {

    // 判断是否为IE
    if (getExplorer() == 'ie') {
        tableToIE(data, name)
    } else {
        tableToNotIE(data, name)
    }
}

const Cleanup = () => {
    window.clearInterval(idTmr);
}

// ie浏览器下执行
const tableToIE = (data, name) => {
    let curTbl = data;
    let oXL = new ActiveXObject("Excel.Application");

    //创建AX对象excel
    let oWB = oXL.Workbooks.Add();
    //获取workbook对象
    let xlsheet = oWB.Worksheets(1);
    //激活当前sheet
    let sel = document.body.createTextRange();
    sel.moveToElementText(curTbl);
    //把表格中的内容移到TextRange中
    sel.select;
    //全选TextRange中内容
    sel.execCommand("Copy");
    //复制TextRange中内容
    xlsheet.Paste();
    //粘贴到活动的EXCEL中

    oXL.Visible = true;
    //设置excel可见属性

    try {
        let fname = oXL.Application.GetSaveAsFilename("Excel.xls", "Excel Spreadsheets (*.xls), *.xls");
    } catch (e) {
        print("Nested catch caught " + e);
    } finally {
        oWB.SaveAs(fname);

        oWB.Close(savechanges = false);
        //xls.visible = false;
        oXL.Quit();
        oXL = null;
        // 结束excel进程,退出完成
        window.setInterval("Cleanup();", 1);
        idTmr = window.setInterval("Cleanup();", 1);
    }
}

// 非ie浏览器下执行
const tableToNotIE = (function () {
    // 编码要用utf-8不然默认gbk会出现中文乱码
    let uri = 'data:application/vnd.ms-excel;base64,',
        template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><meta charset="UTF-8"><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>',
        base64 = function (s) {
            return window.btoa(unescape(encodeURIComponent(s)));

        },

        format = (s, c) => {
            return s.replace(/{(\w+)}/g,
                (m, p) => {
                    return c[p];
                })
        }
    return (table, name) => {
        let ctx = {
            worksheet: name,
            table
        }

        //创建下载
        let link = document.createElement('a');
        link.setAttribute('href', uri + base64(format(template, ctx)));

        link.setAttribute('download', name);


        // window.location.href = uri + base64(format(template, ctx))
        link.click();
    }
})()

// 导出函数(表头,表体,导出名称)
const export2Excel = (theadData, tbodyData, dataname) => {

    let re = /http/ // 字符串中包含http,则默认为图片地址
    let th_len = theadData.length // 表头的长度
    let tb_len = tbodyData.length // 记录条数
    let width = 120 // 设置图片大小
    let height = 120

    // 添加表头信息
    let thead = '<thead><tr style="width:' + 200 + 'px;height:' + 50 + 'px;">'
    for (let i = 0; i < th_len; i++) {
        thead += '<th>' + theadData[i].name + '</th>'
    }
    thead += '</tr></thead>'

    // 添加每一行数据
    let tbody = '<tbody>'
    for (let i = 0; i < tb_len; i++) {
        tbody += '<tr>'
        let row = tbodyData[i] // 获取每一行数据

        for (let h = 0; h < th_len; h++) {
            if (re.test(row[theadData[h].key])) { // 如果为图片,则需要加div包住图片
                console.log(row[theadData[h].key], 'row[key]');
                tbody += '<td style="width:' + width + 'px; height:' + height + 'px; text-align: center; vertical-align: middle"><div style="display:inline"><img src=\'' + row[theadData[h].key] + '\' ' + ' ' + 'width=' + '\"' + width + '\"' + ' ' + 'height=' + '\"' + height + '\"' + '></div></td>'
            } else {
                tbody += '<td style="text-align:center">' + row[theadData[h].key] + '</td>'
            }
        }
        tbody += '</tr>'
    }
    tbody += '</tbody>'

    let table = thead + tbody

    // 导出表格
    exportToExcel(table, dataname)
}

html使用的方法

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <!-- 公共css文件 -->
    <link rel="stylesheet" href="/statics/css/common/common.css">
    <!-- 公共js文件 -->
    <script type="text/javascript" src="/statics/vue_element/common.js"></script>
    <!-- vue方面文件 -->
    <link rel="stylesheet" href="/statics/vue_element/element.css">
    <script src="/statics/vue_element/vue.js"></script>
    <script src="/statics/vue_element/element.js"></script>
    <script src="/statics/vue_element/axios.js"></script>
    <!-- 引入excel导出组件 -->
    <script src="./qdcs.js"></script>
    <title>测试</title>
</head>

<body>
    <div id="app">
        <div @click="ceshi">
            导出测试
        </div>
    </div>
</body>
<script>
    new Vue({
        el: '#app',
        data() {
            return {
                tHeader: [
                    {
                        name:'科室',
                        key:'name',
                    },
                    {
                        name:'部门',
                        key:'color',
                    },
                    {
                        name:'照片',
                        key:'img',
                    }
                ],
                tbody: [
                    {
                        name: '科室1',
                        color: '部门1',
                        img: 'https://nimg.ws.126.net/?url=http%3A%2F%2Fdingyue.ws.126.net%2F2024%2F0510%2F11290a01j00sd90qe001dd000hs00hsg.jpg&thumbnail=660x2147483647&quality=80&type=jpg'
                    },
                    {
                        name: '科室12',
                        color: '部门2',
                        img: 'https://nimg.ws.126.net/?url=http%3A%2F%2Fdingyue.ws.126.net%2F2024%2F0510%2F11290a01j00sd90qe001dd000hs00hsg.jpg&thumbnail=660x2147483647&quality=80&type=jpg'
                    },
                    {
                        name: '科室13',
                        color: '部门3',
                        img: 'https://nimg.ws.126.net/?url=http%3A%2F%2Fdingyue.ws.126.net%2F2024%2F0510%2F11290a01j00sd90qe001dd000hs00hsg.jpg&thumbnail=660x2147483647&quality=80&type=jpg'
                    },
                    {
                        name: '科室14',
                        color: '部门4',
                        img: 'https://nimg.ws.126.net/?url=http%3A%2F%2Fdingyue.ws.126.net%2F2024%2F0510%2F11290a01j00sd90qe001dd000hs00hsg.jpg&thumbnail=660x2147483647&quality=80&type=jpg'
                    },
                    {
                        name: '科室15',
                        color: '部门5',
                        img: 'https://nimg.ws.126.net/?url=http%3A%2F%2Fdingyue.ws.126.net%2F2024%2F0510%2F11290a01j00sd90qe001dd000hs00hsg.jpg&thumbnail=660x2147483647&quality=80&type=jpg'
                    }
                ]
            }
        },
        methods: {
            ceshi(){
                export2Excel(this.tHeader, this.tbody, '我爱花朵')
            }
        }
    })
</script>

</html>```

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
你可以使用以下步骤在 Vue 中导出 Excel 表格: 1. 安装 `xlsx` 和 `file-saver` 库: ```bash npm install xlsx file-saver --save ``` 2. 在 Vue 组件中引入这两个库: ```javascript import XLSX from 'xlsx'; import FileSaver from 'file-saver'; ``` 3. 创建一个方法来实现导出 Excel 表格的逻辑: ```javascript exportExcel() { const worksheet = XLSX.utils.json_to_sheet(this.tableData); const workbook = XLSX.utils.book_new(); XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1'); const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' }); const data = new Blob([excelBuffer], { type: 'application/octet-stream' }); FileSaver.saveAs(data, 'table.xlsx'); } ``` 在上面的代码中,我们首先将表格数据转换工作表对象,然后将工作表对象添加到工作簿对象中。接着,我们使用 `XLSX.write` 方法将工作簿对象转换 Excel 文件的二进制数据。最后,我们将二进制数据保存到 `Blob` 对象中,并使用 `FileSaver.saveAs` 方法将其保存为 Excel 文件。 4. 在 Vue 模板中添加一个按钮来触发导出方法: ```html <template> <div> <button @click="exportExcel">导出 Excel</button> <table> <thead> <tr> <th>Name</th> <th>Age</th> <th>Gender</th> </tr> </thead> <tbody> <tr v-for="item in tableData" :key="item.id"> <td>{{ item.name }}</td> <td>{{ item.age }}</td> <td>{{ item.gender }}</td> </tr> </tbody> </table> </div> </template> ``` 在上面的代码中,我们添加了一个按钮来触发导出方法,并在表格中展示了数据。 这样,你就可以在 Vue 中轻松地实现导出 Excel 表格的功能了。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

接口写好了吗

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值