VUE通用后台管理系统(四)前端导出文件(CSV、XML、HTML、PDF、EXCEL)

VUE通用后台管理系统(四)前端导出文件(CSV、XML、HTML、PDF、EXCEL)

常见的导出格式:CSV、XML、HTML、PDF、EXCEL

1)准备工作

安装所需相关依赖

javascript">npm i html2canvas --save
npm i jspdf --save

npm i xlsx --save
npm i file-saver --save

前两个是PDF格式需要的依赖,后两个是excel格式所需,如果没有需求这两种格式的可以忽略这一步

然后画页面

 

页面效果

2)导出CSV格式的文件

新建src/utils/utils.js文件

写入exportCsv方法,columns为表头,dataList数据,filename导出文件名称

// 导出csv
export function exportCsv(columns, dataList, fileName) {
  let title = columns.map(item => item.title);
  let keyArray = columns.map(item => item.key);
  let str = [];
  str.push(title.join(',') + '\n');
  for (let i = 0; i < dataList.length; i++) {
    const temp = [];
    for (let j = 0; j < keyArray.length; j++) {
      temp.push(dataList[i][keyArray[j]]);
    }
    str.push(temp.join(',') + '\n');
  } 
  console.log(str)
  let uri = 'data:text/csv;charset=utf-8,\ufeff' + encodeURI***ponent(str.join(''));
  let downloadLink = document.createElement('a');
  downloadLink.href = uri;
  downloadLink.download = fileName;
  document.body.appendChild(downloadLink);
  downloadLink.click();
  document.body.removeChild(downloadLink);
}

页面使用

先引人方法

import { exportCsv, exportXml, exportHtml, exportPDF, exportExcel } from "@/utils/utils"

再调用

    handleExprotData() {
        //表头
      let allColumns = []
      this.$refs.singleTable.$children.forEach(obj => {
        if (obj.label !== undefined && obj.prop !== undefined) {
          allColumns.push({ "title": obj.label, "key": obj.prop })
        }
      })

      //this.checkboxList是勾选的需要导出的数据
      console.log(JSON.parse(JSON.stringify("allColumns -----------" , allColumns)))
      console.log(JSON.parse(JSON.stringify("this.checkboxList ----------------" , this.checkboxList)))
      this.exportForm.exportFormat == 0 && exportCsv(allColumns, this.checkboxList, "CP信息");

}

效果

3)导出XML格式的文件

在utils.js写入

// 导出xml格式
export function exportXml(columns, dataList, fileName) {
  let str = '<?xml version="1.0" encoding="utf-8" ?>\n<dataSource>\n';
  dataList.forEach(dataItem => {
    str += `<dataItem>\n`;
    columns.forEach(columnsItem => {
      str += `<${columnsItem.key}>${dataItem[columnsItem.key]}</${columnsItem.key}>\n`;
    });
    str += `</dataItem>\n`;
  });
  str += '</dataSource>';
  let downloadLink = document.createElement('a');
  let uri = window.URL.createObjectURL(new Blob([str], { type: 'text/plain;charset=utf-8,\ufeff' }));
  downloadLink.href = uri;
  downloadLink.download = `${fileName}.xml`;
  downloadLink.click();
  window.URL.revokeObjectURL(uri);
}

然后再页面引入、调用,和csv格式一样

    handleExprotData() {
        //表头
      let allColumns = []
      this.$refs.singleTable.$children.forEach(obj => {
        if (obj.label !== undefined && obj.prop !== undefined) {
          allColumns.push({ "title": obj.label, "key": obj.prop })
        }
      })

      //this.checkboxList是勾选的需要导出的数据
      console.log(JSON.parse(JSON.stringify("allColumns -----------" , allColumns)))
      console.log(JSON.parse(JSON.stringify("this.checkboxList ----------------" , this.checkboxList)))
      this.exportForm.exportFormat == 0 && exportCsv(allColumns, this.checkboxList, "CP信息");
      this.exportForm.exportFormat == 1 && exportXml(allColumns, this.checkboxList, "CP信息");

}

效果

4)导出HTML格式的文件

// 导出html格式
export function exportHtml(columns, dataList, fileName) {
  let str = '<table border="1" style="border-collapse: collapse;min-width:80%;margin:0 10%;">\n';
  columns.forEach(columnsItem => {
    str += `<th>${columnsItem.title}</th>\n`;
  });
  dataList.forEach(dataItem => {
    str += `<tr>\n`;
    columns.forEach(columnsItem => {
      str += `<td>${dataItem[columnsItem.key]}</td>\n`;
    });
    str += `</tr>\n`;
  });
  str += '</table>';
  let html = `<!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta http-equiv="X-UA-***patible" content="IE=edge">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Document</title>
    </head>
    <body>
      <h2 style="text-align:center">
        ${fileName}
      </h2>
      <div style="width:100%">
        ${str}
      </div>
    </body>
    </html>`;

  let downloadLink = document.createElement('a');
  let uri = window.URL.createObjectURL(new Blob([html], { type: 'text/html;charset=utf-8,\ufeff' }));
  downloadLink.href = uri;
  downloadLink.download = `${fileName}.html`;
  downloadLink.click();
  window.URL.revokeObjectURL(uri);
}

页面引入,调用

页面上加一行

this.exportForm.exportFormat == 2 && exportHtml(allColumns, this.checkboxList, "CP信息");

就可以了

效果

5)导出PDF格式的文件

utils引入依赖

import html2canvas from 'html2canvas';
import { jsPDF } from "jspdf"
// 导出pdf格式
export function exportPDF(columns, dataList, fileName) {
  let str = '<table border="1" style="border-collapse: collapse;min-width:80%;margin:0 10%;">\n';
  columns.forEach(columnsItem => {
    str += `<th>${columnsItem.title}</th>\n`;
  });
  dataList.forEach(dataItem => {
    str += `<tr>\n`;
    columns.forEach(columnsItem => {
      str += `<td>${dataItem[columnsItem.key]}</td>\n`;
    });
    str += `</tr>\n`;
  });
  str += '</table>';
  let ele = document.createElement('div');
  ele.innerHTML = `<h2 style="text-align:center">
    ${fileName}
  </h2>
  <div style="width:100%">
    ${str}
  </div>`;
  document.body.appendChild(ele);

  // var w = ele.offsetwidth; //获得该容器的宽
  // var h = ele.offsetwidth; //获得该容器的高
  // var offsetTop = ele.offsetTop + 24; //获得该容器到文档顶部的距离
  // var offsetLeft = ele.offsetLeft + 24; //获得该容器到文档最左的距离
  var w = 960; //获得该容器的宽
  var h = 1024; //获得该容器的高
  var offsetTop = 24; //获得该容器到文档顶部的距离
  var offsetLeft = 24; //获得该容器到文档最左的距离

  var canvas = document.createElement('canvas');
  var abs = 0;
  var win_i = document.body.clientwidth; //获得当前可视窗口的宽度(不包含滚动条)
  var win_o = window.innerwidth; //获得当前窗口的宽度(包含滚动条)
  if (win_o > win_i) {
    abs = (win_o - win_i) / 2; //获得滚动条长度的—半
  }
  canvas.width = w * 2; //将回布宽&&高放大两倍
  canvas.height = h * 2;
  var context = canvas.getContext('2d');
  context.scale(2, 2);
  context.translate(-offsetLeft - abs, -offsetTop);
  //这里默认横向没有滚动条的情况,因为offset.Left(),有无滚动条的时候存在差值,因此 transLate的时候,要把这个差值去掉
  html2canvas(ele, {
    allowTaint: true,
    scale: 2, //提升画面质量,但是会增加文件大小
  }).then(function(canvas) {
    var contentwidth = canvas.width;
    var contentHeight = canvas.height;
    //一页pdf显示htmL页面生成的canvas高度;
    var pageHeight = (contentwidth / 592.28) * 841.89;
    //未生成pdf 的htmL页面高度
    var leftHeight = contentHeight;
    //页面偏移
    var position = 0;
    //a4纸的尺寸[ 595.28,841.89],html页面生成的canvas在pdf中图片的宽高
    var imgwidth = 595.28;
    var imgHeight = (592.28 / contentwidth) * contentHeight;
    var pageData = canvas.toDataURL(' image/jpeg ', 1.0);
    var pdf = new jsPDF('', 'pt', 'a4');
    console.log(pdf);
    //有两个高度需要区分,一个是htmL页面的实际高度,和生成pdf的页面高度(841.89) 当内容未超过pdf—页显示的范围,无需分页
    if (leftHeight < pageHeight) {
      pdf.addImage(pageData, 'JPEG', 0, 0, imgwidth, imgHeight);
    } else {
      //分页
      while (leftHeight > 0) {
        pdf.addImage(pageData, 'JPEG', 0, position, imgwidth, imgHeight);
        leftHeight -= pageHeight;
        position -= 841.89;
        //避免添加空白页
        if (leftHeight > 0) {
          pdf.addPage();
        }
      }
    }
    pdf.save(`${fileName}.pdf`);
    document.body.removeChild(ele);
  });
}
const s2ab = s => {
  var buf;
  if (typeof ArrayBuffer !== 'undefined') {
    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
  } else {
    buf = new Array(s.length);
    for (var i = 0; i != s.length; ++i) buf[i] = s.charCodeAt(i) & 0xFF;
    return buf;
  }
} 

 页面引入、调用

this.exportForm.exportFormat == 3 && exportPDF(allColumns, this.checkboxList, "CP信息");

效果

 6)导出EXCEL格式的文件

引入依赖

import * as XLSX from 'xlsx'
import fs from 'file-saver'
// 导出excel格式
export function exportExcel(columns, dataList, filename) { 
  dataList.forEach(item => {
    for (let i in item) {
      if (columns.hasOwnProperty(i)) {
        item[columns[i]] = item[i];
      }
      delete item[i]; //删除原先的对象属性
    }
  })
  let sheetName = filename + ".xlsx" //excel的文件名称
  console.log(sheetName)
  let wb = XLSX.utils.book_new() //工作簿对象包含一SheetNames数组,以及一个表对象映射表名称到表对象。XLSX.utils.book_new实用函数创建一个新的工作簿对象。
  console.log(wb)
  let ws = XLSX.utils.json_to_sheet(dataList, {
    header: Object.values(columns)
  }) //将JS对象数组转换为工作表。
  wb.SheetNames.push(sheetName)
  wb.Sheets[sheetName] = ws
  const defaultCellStyle = {
    font: {
      name: "Verdana",
      sz: 13,
      color: "FF00FF88"
    },
    fill: {
      fgColor: {
        rgb: "FFFFAA00"
      }
    }
  }; //设置表格的样式
  let wopts = {
    bookType: 'xlsx',
    bookSST: false,
    type: 'binary',
    cellStyles: true,
    defaultCellStyle: defaultCellStyle,
    showGridLines: false
  } //写入的样式
  let wbout = XLSX.write(wb, wopts)
  let blob = new Blob([s2ab(wbout)], {
    type: 'application/octet-stream'
  })
  fs.saveAs(blob, filename + '.xlsx')
}

这个页面调用与别的格式不同

      //excel格式专用表头
      if (this.exportForm.exportFormat == 4) {
        let excelColumns = {}
        this.$refs.singleTable.$children.forEach(obj => {
          if (obj.label !== undefined && obj.prop !== undefined) {
            excelColumns[obj.prop] = obj.label
          }
        })
        exportExcel(excelColumns, this.checkboxList, "CP信息");
        return
      } 

效果看着与csv文件一样的

转载请说明出处内容投诉
CSS教程_站长资源网 » VUE通用后台管理系统(四)前端导出文件(CSV、XML、HTML、PDF、EXCEL)

发表评论

欢迎 访客 发表评论

一个令你着迷的主题!

查看演示 官网购买