vue3 jspdf,element table 导出excel、pdf,横板竖版分页

本文主要是介绍vue3 jspdf,element table 导出excel、pdf,横板竖版分页,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

多个表格需要,pdf需要的格式与原本展示的表格样式不同

1.创建一个新的表格,设置pdf需要的样式,用vue的h函数放入dom中

2.excel用xlxs插件直接传入新建el-table的dom,直接导出

3.pdf导出类似excel黑色边框白底黑字的文件,把el-table改成需要的样式,

由于table内部的表格是由td,tr绘制的所以表头和表格本身必须使用插槽写div给固定的表格宽度和高度配合

 :row-style="rowStyle":cell-style="cellStyle":header-cell-style="headerCellStyle"

4.导pdf使用jspdf插件,只能接受图片格式(base64/png、jpg)等,使用html2Canvas先把dom转成canvas在转成图片

5.pdf文件的尺寸和分页需要根据需求设置,主要方法是

创建pdf文件对象let pdf = new jsPDF('p', 'mm', 'a4'); 
为pdf页添加图片内容
pdf.addImage(testImage,'JPEG',10,10,190,Math.min(a4h, (190 * page.height) / page.width),);
新增一页
pdf.addPage();

demo

exportPDFExcel.js

导出方法调出弹窗,调用addTable方法dom创建成功后处理导出事件

import { ElMessageBox, ElButton, ElLoading, ElTable } from 'element-plus'
import { h, nextTick } from 'vue'
import { request } from "@/utils/request";
import Menu from "./creatTable.js";
import { saveAs } from "file-saver";
import XLSX from "xlsx";
import { removeTable } from "./creatTable";
import html2Canvas from 'html2canvas';
import jsPDF from 'jspdf';
let fileName = ''
let fileType = ''
let mesBox = null
let loading = null
//导选择创口,pdfexcel
export function exportMessageBox(params, name, columns) {ElMessageBox({title: '请选择导出格式',message: h('p', null, [h('div', {class: 'el-button el-button--primary el-button--default', innerHTML: 'Excel', onClick: () => {getData(params, name, columns, 'xlsx')}}),h('div', {class: 'el-button el-button--primary el-button--default', innerHTML: 'PDF', onClick: () => {getData(params, name, columns, 'pdf')}})]),'showConfirmButton': false})}
function getData(params, name, columns, type) {
//关闭弹窗,打开loadingmesBox = document.querySelector(".el-message-box__headerbtn");mesBox.click();loading = ElLoading.service({text: "正在下载数据,请稍候",background: "rgba(0, 0, 0, 0.7)",});fileName = namefileType = type//业务操作,调接口抽数据request.get(params.url, params).then((response) => {if (response.code === 200) {let list = response.rows;
//创建table,传递列和数据组Menu.addTable(list, columns)}});
}
export function downFile(params) {
//构建文件名const currentDate = new Date();const year = currentDate.getFullYear();const month = String(currentDate.getMonth() + 1).padStart(2, "0");const day = String(currentDate.getDate()).padStart(2, "0");const hours = String(currentDate.getHours()).padStart(2, "0");const minutes = String(currentDate.getMinutes()).padStart(2, "0");const seconds = String(currentDate.getSeconds()).padStart(2, "0");const formattedDate = `${year}_${month}_${day}_${hours}_${minutes}_${seconds}`;const txt = `${fileName}${formattedDate}.${fileType}`nextTick(() => {
//获取到domconst table = document.querySelector("#table_export_content_one")if (fileType === 'xlsx') {
//导出excel,直接传dom给XLSX用其方法const workbook = XLSX.utils.table_to_book(table,{raw: true, //有的是日期、小数等格式,直接乱码#。所以这里直接保留原始字符串});const wbout = XLSX.write(workbook, {bookType: "xlsx",bookSST: true,type: "array",});saveAs(new Blob([wbout], {type: "application/octet-stream",}),txt);removeTable()loading.close()}else {downPDF()}});
}
//导出pdf
function downPDF() {const table = document.querySelector("#table_export_content_one")let title = fileName
//表格整体转canvashtml2Canvas(table, {removeContainer: true,useCORS: true,}).then((canvas) => {let pdf = new jsPDF('p', 'mm', 'a4'); //A4纸,纵向
//a4w和a4h在列少的情况可以直接配210*297,列多横板分页需要配成表格宽度*一页需要放的表格数,高度类比let ctx = canvas.getContext('2d'),a4w = 154 * 8,a4h = 25 * 100, //A4大小,210mm x 297mm,四边各保留10mm的边距,显示区域190x277renderedWidth = 0let kss = truewhile (renderedWidth <= canvas.width) {let renderedHeight = 0while (renderedHeight <= canvas.height) {let page = document.createElement('canvas');page.width = Math.min(a4w, canvas.width - renderedWidth);page.height = Math.min(a4h, canvas.height - renderedHeight); //可能内容不足一页//getImage获取一页的选区转成图片,参数为x,y,width,heightpage.getContext('2d').putImageData(ctx.getImageData(renderedWidth,renderedHeight,Math.min(a4w, canvas.width - renderedWidth),Math.min(a4h, canvas.height - renderedHeight),),0,0,);const testImage = page.toDataURL('image/jpeg', 1.0)
if(!kss){const allImage = canvas.toDataURL('image/jpeg', 1.0)const a = document.createElement("a");a.download =  '0123456.PNG';a.href = allImage;document.body.appendChild(a);a.click();document.body.removeChild(a);kss=true
}
//将获取的该页image加入到pdf中pdf.addImage(testImage,'JPEG',10,10,190,Math.min(a4h, (190 * page.height) / page.width),); //添加图像到页面,保留10mm边距renderedHeight += a4h;if (renderedHeight < canvas.height) {pdf.addPage(); //如果后面还有内容,添加一个空页}  }renderedWidth += a4w;if (renderedWidth < canvas.width) {pdf.addPage(); //如果后面还有内容,添加一个空页}}pdf.save(title + '.pdf');
//移除临时创建的table,removeTable()loading.close()})
}function formatJson(filterVal, list) {return list.map((v) =>filterVal.map((j) => {// 进行日期格式化const arr = j.split(".");if (arr.length === 1) {return v[j];} else if (arr.length === 2 && eval("v." + arr[0])) {return eval("v." + j);} else if (arr.length === 3 &&eval("v." + arr[0]) &&eval("v." + arr[0] + "." + arr[1])) {return eval("v." + j);}return "";}));
}

creatTable.js

创建table方法和移除table方法

import { createVNode, render ,h, nextTick} from "vue";
import tableElement from "./index.vue";import {downFile} from './exportPDFExcel'//      定义一个div容器
const div = document.createElement("div");document.body.appendChild(div);
export default {addTable(list, columnsProp,) {const vnode = createVNode(tableElement, { list, columnsProp });render(vnode, div);nextTick(()=>{downFile()})},
};
export const removeTable = function () {render(null, div);
};

index.vue

虚拟构建的table的dom内容,和参数处理

<template><div class="export_box_table"><div class="export_table"><el-table:row-style="rowStyle":cell-style="cellStyle":header-cell-style="headerCellStyle"id="table_export_content_one":data="test"isShowDynamicColumn><el-table-columnv-for="item in columns":label="item.label":prop="item.prop"><template #header="scope"><div :style="{ width: cellHeight + 'px' }">{{ item.label }}</div></template><template #default="scope"><div:style="{'background-color': getStyle1(scope.row, item),width: cellHeight + 'px',color: '#000',}">44444</div></template></el-table-column></el-table></div></div>
</template><script setup>
import dciTableColumn from "@/views/admin/dci/components/dciTableColumn.vue";
import { ElTable, ElTableColumn } from "element-plus";
import { computed } from "vue";const { proxy } = getCurrentInstance();
const columns = ref([]);
const cellHeight = ref(150);
const tableWidth = computed(() => {return (cellHeight.value+26) * (columns.value.length) + "px";
});
//测试数据
let testObj = {createBy: null,createTime: "2023-11-20 16:29:57",instPowerT: 0,instPowerMw: 0,instCoal: 0,instGas: 0,instWater: 0,instElec: 0,instHeat: 301.73,}
let test = new Array(200).fill(testObj);
//测试结束
defineProps({list: {type: Array,default() {return [];},},columnsProp: {type: Array,default() {return [];},},
});initTable();
function initTable() {columns.value = [];proxy.columnsProp.forEach((item, index) => {if (item.props) {initItem(item.props);columns.value.push(item.props);}});
}function rowStyle() {return {// "background-color": "rgba(2,5,2,0.2)",// "background-color": "rgba(7,29,68,1)",color: "#000",};
}
function cellStyle() {let hei = "2px";let style = {border: "1px solid #000",// "background-color": "rgba(7,29,68,1)","background-color": "#fff",padding: "0px",height: hei,"line-height": hei,};return style;
}
function headerCellStyle() {return {"background-color": "#fff!important",width: "250px",border: "1px solid #000",color: "#000",height: "32px!important","font-size": "14px",padding: "0px","line-height": "32px",};
}function initItem(item) {item.magnification = item.magnification ? item.magnification : 1;item.suffix = item.suffix ? item.suffix : "";item.color = item.color ? item.color : "";item.type = item.type ? item.type : "";item.tooltip = item.tooltip ? item.tooltip : "";item.chuhui = item.chuhui ? item.chuhui : "";item.ziduanName = item.ziduanName ? item.ziduanName : "";item.ziduanValue = item.ziduanValue ? item.ziduanValue : "";item.ziduanColor = item.ziduanColor ? item.ziduanColor : "";item.isPhone = item.isPhone ? item.isPhone : false;item.time = item.time ? item.time : false;item.fixedNumber = item.fixedNumber ? item.fixedNumber : 1;item.export = item.export ? item.export : false;
}</script><style scoped>.export_box_table{width: 800px;overflow: auto;/* position: fixed; */height: 500px;/* z-index: 500; *//* top: 0px; */background-color: rgb(0, 255, 179);}
.export_table {width: fit-content;height: 500px;background-color: red;/* position: absolute;top: 0px;left: 0px; */overflow: auto;
}
#table_export_content_one {width: v-bind(tableWidth);
}
</style>
<style lang="scss" scoped>
.column_visible {position: absolute;z-index: 9;left: 100px;top: -0px;
}
</style>
<style>
.hover_row_pointer:hover {cursor: pointer;
}
</style>

这篇关于vue3 jspdf,element table 导出excel、pdf,横板竖版分页的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/951286

相关文章

Vue项目的甘特图组件之dhtmlx-gantt使用教程和实现效果展示(推荐)

《Vue项目的甘特图组件之dhtmlx-gantt使用教程和实现效果展示(推荐)》文章介绍了如何使用dhtmlx-gantt组件来实现公司的甘特图需求,并提供了一个简单的Vue组件示例,文章还分享了一... 目录一、首先 npm 安装插件二、创建一个vue组件三、业务页面内 引用自定义组件:四、dhtmlx

使用Python创建一个能够筛选文件的PDF合并工具

《使用Python创建一个能够筛选文件的PDF合并工具》这篇文章主要为大家详细介绍了如何使用Python创建一个能够筛选文件的PDF合并工具,文中的示例代码讲解详细,感兴趣的小伙伴可以了解下... 目录背景主要功能全部代码代码解析1. 初始化 wx.Frame 窗口2. 创建工具栏3. 创建布局和界面控件4

Python进行PDF文件拆分的示例详解

《Python进行PDF文件拆分的示例详解》在日常生活中,我们常常会遇到大型的PDF文件,难以发送,将PDF拆分成多个小文件是一个实用的解决方案,下面我们就来看看如何使用Python实现PDF文件拆分... 目录使用工具将PDF按页数拆分将PDF的每一页拆分为单独的文件将PDF按指定页数拆分根据页码范围拆分

Vue ElementUI中Upload组件批量上传的实现代码

《VueElementUI中Upload组件批量上传的实现代码》ElementUI中Upload组件批量上传通过获取upload组件的DOM、文件、上传地址和数据,封装uploadFiles方法,使... ElementUI中Upload组件如何批量上传首先就是upload组件 <el-upl

前端知识点之Javascript选择输入框confirm用法

《前端知识点之Javascript选择输入框confirm用法》:本文主要介绍JavaScript中的confirm方法的基本用法、功能特点、注意事项及常见用途,文中通过代码介绍的非常详细,对大家... 目录1. 基本用法2. 功能特点①阻塞行为:confirm 对话框会阻塞脚本的执行,直到用户作出选择。②

Java实战之利用POI生成Excel图表

《Java实战之利用POI生成Excel图表》ApachePOI是Java生态中处理Office文档的核心工具,这篇文章主要为大家详细介绍了如何在Excel中创建折线图,柱状图,饼图等常见图表,需要的... 目录一、环境配置与依赖管理二、数据源准备与工作表构建三、图表生成核心步骤1. 折线图(Line Ch

Python3脚本实现Excel与TXT的智能转换

《Python3脚本实现Excel与TXT的智能转换》在数据处理的日常工作中,我们经常需要将Excel中的结构化数据转换为其他格式,本文将使用Python3实现Excel与TXT的智能转换,需要的可以... 目录场景应用:为什么需要这种转换技术解析:代码实现详解核心代码展示改进点说明实战演练:从Excel到

如何使用CSS3实现波浪式图片墙

《如何使用CSS3实现波浪式图片墙》:本文主要介绍了如何使用CSS3的transform属性和动画技巧实现波浪式图片墙,通过设置图片的垂直偏移量,并使用动画使其周期性地改变位置,可以创建出动态且具有波浪效果的图片墙,同时,还强调了响应式设计的重要性,以确保图片墙在不同设备上都能良好显示,详细内容请阅读本文,希望能对你有所帮助...

CSS3 最强二维布局系统之Grid 网格布局

《CSS3最强二维布局系统之Grid网格布局》CS3的Grid网格布局是目前最强的二维布局系统,可以同时对列和行进行处理,将网页划分成一个个网格,可以任意组合不同的网格,做出各种各样的布局,本文介... 深入学习 css3 目前最强大的布局系统 Grid 网格布局Grid 网格布局的基本认识Grid 网

HTML5中下拉框<select>标签的属性和样式详解

《HTML5中下拉框<select>标签的属性和样式详解》在HTML5中,下拉框(select标签)作为表单的重要组成部分,为用户提供了一个从预定义选项中选择值的方式,本文将深入探讨select标签的... 在html5中,下拉框(<select>标签)作为表单的重要组成部分,为用户提供了一个从预定义选项中