vue 前端导出word、excel、pdf

2,119 阅读2分钟

三种格式都需要使用的插件有FileSaver

npm install --save xlsx file-saver

一、导出excel文件

excel文件导出的格式是最符合要求的,数据表格分类清晰,无乱码和错位现象。

1.首先确认vue项目已经成功搭建,element等已经下载并在组件内进行引用,excel格式导出需下载XLSX插件,然后在需要使用的组件内的script标签中进行引入


import FileSaver from "file-saver";
import XLSX from "xlsx";

下载方法为:

methods: {
    downLoad(){
      var wb = XLSX.utils.table_to_book(document.querySelector("#file"));
        var wbout = XLSX.write(wb, {
          bookType: "xlsx",
          bookSST: true,
          type: "array"
        });
        try {
          FileSaver.saveAs(
            new Blob([wbout], { type: "application/octet-stream" }),
            "表格"+ ".xlsx" //  name+'.xlsx'表示导出的excel表格名字
          );
        } catch (e) {
          if (typeof console !== "undefined") console.log(e, wbout);
        }
        return wbout;
    }
  }

参考链接:blog.csdn.net/weixin_4242…

二、导出pdf文件 首先需要安装两个依赖 第一个.将页面html转换成图片

npm install --save html2canvas 

第二个.将图片生成pdf

npm install jspdf --save

然后创建一个htmlToPdf.js文件,在需要使用的组件内进行引入,htmlToPdf.js内容如下:


import html2canvas from 'html2canvas'
import jsPDF from 'jspdf'
export default{
    install (Vue, options) {
        Vue.prototype.getPdf = function (htmlTitle,currentTime) {
            var element = document.getElementById("file");
            html2canvas(element, {
                logging:false
            }).then(function(canvas) {
                var pdf = new jsPDF('p', 'mm', 'a4');    //A4纸,纵向
                var ctx = canvas.getContext('2d'),
                    a4w = 190, a4h = 277,    //A4大小,210mm x 297mm,四边各保留10mm的边距,显示区域190x277
                    imgHeight = Math.floor(a4h * canvas.width / a4w),    //按A4显示比例换算一页图像的像素高度
                    renderedHeight = 0;

            while(renderedHeight < canvas.height) {
                var page = document.createElement("canvas");
                page.width = canvas.width;
                page.height = Math.min(imgHeight, canvas.height - renderedHeight);//可能内容不足一页

                //用getImageData剪裁指定区域,并画到前面创建的canvas对象中
                page.getContext('2d').putImageData(ctx.getImageData(0, renderedHeight, canvas.width, Math.min(imgHeight, canvas.height - renderedHeight)), 0, 0);
                pdf.addImage(page.toDataURL('image/jpeg', 1.0), 'JPEG', 10, 10, a4w, Math.min(a4h, a4w * page.height / page.width));    //添加图像到页面,保留10mm边距

                renderedHeight += imgHeight;
                if(renderedHeight < canvas.height)
                    pdf.addPage();//如果后面还有内容,添加一个空页
            }
            
            pdf.save(htmlTitle);
        });
    }
}
}

成功引入后,在组件内直接调用该方法

methods: {
    downLoad(){
      this.getPdf('表格');//参数是下载的pdf文件名
    }
  }

导出的时候button按钮放在了选择器内,所以下载的文件包含了button,实际可根据自己的需求进行适当的修改,另外和我们日常看到的pdf文件有一定区别,但目前就我查阅到的纯前端导出pdf文件应该算比较好的效果了。 注意,js里面的dom操作选择器应该和要下载的dom选择器一致。 参考链接:blog.csdn.net/pratise/art… 三、导出word文件 使用的是jquery的插件export进行导出。所以需要先安装jquery, 首先安装jquery

npm install jquery --save

在项目 build 里的webpack.base.conf.js 里加载webpack文件,注意,要放在配置文件第一行;

const  webpack = require('webpack')

在module.exports的最后加入

// 添加代码
plugins: [
 new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery",
jquery: "jquery",
"window.jQuery": "jquery"
 })
],

1.引入jquery

import $ from "jquery"

2.引入exportJs

import wordExport from '@/utils/jquery.word.export'

我将export.js放在src的utils文件夹下,内容如下

//导入js文件
import saveAs from "file-saver"
import $ from "jquery"
 
if (typeof jQuery !== "undefined" && typeof saveAs !== "undefined") {
    (function() {
        $.fn.wordExport = function(fileName,rules) {
            fileName = typeof fileName !== 'undefined' ? fileName : "jQuery-Word-Export";
            var static_ = {
                mhtml: {
                    top: "Mime-Version: 1.0\nContent-Base: " + location.href + "\nContent-Type: Multipart/related; boundary=\"NEXT.ITEM-BOUNDARY\";type=\"text/html\"\n\n--NEXT.ITEM-BOUNDARY\nContent-Type: text/html; charset=\"utf-8\"\nContent-Location: " + location.href + "\n\n<!DOCTYPE html>\n<html>\n_html_</html>",
                    head: "<head>\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\n<style>\n_styles_\n</style>\n</head>\n",
                    body: "<body>_body_</body>"
                }
            };
            var options = {
                maxWidth: 624
            };
            // Clone selected element before manipulating it
            var markup = $(this).clone();


        // Remove hidden elements from the output
        markup.each(function() {
            var self = $(this);
            if (self.is(':hidden'))
                self.remove();
        });

        // Embed all images using Data URLs
        var images = Array();
        var img = markup.find('img');
        for (var i = 0; i < img.length; i++) {
            //如果导出的word文件里面包含线上的图片
            // Calculate dimensions of output image
            var width = Math.min(img[i].width, options.maxWidth);
            var height = img[i].height * (width / img[i].width);
            // Create canvas for converting image to data URL
            //这是添加的代码--------------------------------------------
            var img_id = "#"+img[i].id;
            $('<canvas>').attr("id", "test_word_img_" + i).width(width).height(height).insertAfter(img_id);

           /*
           //如果导出的word文件里面包含本地图片用这一段,如果都包含,要另外研究一下
           // Calculate dimensions of output image
            var w = Math.min(img[i].width, options.maxWidth);
            var h = img[i].height * (w / img[i].width);
            // Create canvas for converting image to data URL
            var canvas = document.createElement("CANVAS");
            canvas.width = w;
            canvas.height = h;
            // Draw image to canvas
            var context = canvas.getContext('2d');
            context.drawImage(img[i], 0, 0, w, h);
            // Get data URL encoding of image
            var uri = canvas.toDataURL("image/png");
            $(img[i]).attr("src", img[i].src);
            img[i].width = w;
            img[i].height = h;
            // Save encoded image to array
            images[i] = {
                type: uri.substring(uri.indexOf(":") + 1, uri.indexOf(";")),
                encoding: uri.substring(uri.indexOf(";") + 1, uri.indexOf(",")),
                location: $(img[i]).attr("src"),
                data: uri.substring(uri.indexOf(",") + 1)
            };
            */
        }

        // Prepare bottom of mhtml file with image data
        var mhtmlBottom = "\n";
        for (var i = 0; i < images.length; i++) {
            mhtmlBottom += "--NEXT.ITEM-BOUNDARY\n";
            mhtmlBottom += "Content-Location: " + images[i].location + "\n";
            mhtmlBottom += "Content-Type: " + images[i].type + "\n";
            mhtmlBottom += "Content-Transfer-Encoding: " + images[i].encoding + "\n\n";
            mhtmlBottom += images[i].data + "\n\n";
        }
        mhtmlBottom += "--NEXT.ITEM-BOUNDARY--";

        //TODO: load css from included stylesheet
        var styles = rules;

        // Aggregate parts of the file together
        var fileContent = static_.mhtml.top.replace("_html_", static_.mhtml.head.replace("_styles_", styles) + static_.mhtml.body.replace("_body_", markup.html())) + mhtmlBottom;

        // Create a Blob with the file contents
        var blob = new Blob([fileContent], {
            type: "application/msword;charset=utf-8"
        });
        saveAs.saveAs(blob, fileName + ".doc");
    };
})(jQuery);
} else {
    if (typeof jQuery === "undefined") {
        console.error("jQuery Word Export: missing dependency (jQuery)");
    }
    if (typeof saveAs === "undefined") {
        console.error("jQuery Word Export: missing dependency (FileSaver.js)");
    }
}

然后在组件内调用方法

downLoad(){
      $("#pdfDom").wordExport('表格');//参数是下载的word文件名
    }

文章中主要代码如下:

参考链接:blog.csdn.net/sinat_37984…

摘自:blog.csdn.net/weixin_4386…