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

相关文章

基于Python实现进阶版PDF合并/拆分工具

《基于Python实现进阶版PDF合并/拆分工具》在数字化时代,PDF文件已成为日常工作和学习中不可或缺的一部分,本文将详细介绍一款简单易用的PDF工具,帮助用户轻松完成PDF文件的合并与拆分操作... 目录工具概述环境准备界面说明合并PDF文件拆分PDF文件高级技巧常见问题完整源代码总结在数字化时代,PD

Python实现Word转PDF全攻略(从入门到实战)

《Python实现Word转PDF全攻略(从入门到实战)》在数字化办公场景中,Word文档的跨平台兼容性始终是个难题,而PDF格式凭借所见即所得的特性,已成为文档分发和归档的标准格式,下面小编就来和大... 目录一、为什么需要python处理Word转PDF?二、主流转换方案对比三、五套实战方案详解方案1:

SpringBoot集成EasyExcel实现百万级别的数据导入导出实践指南

《SpringBoot集成EasyExcel实现百万级别的数据导入导出实践指南》本文将基于开源项目springboot-easyexcel-batch进行解析与扩展,手把手教大家如何在SpringBo... 目录项目结构概览核心依赖百万级导出实战场景核心代码效果百万级导入实战场景监听器和Service(核心

基于Python Playwright进行前端性能测试的脚本实现

《基于PythonPlaywright进行前端性能测试的脚本实现》在当今Web应用开发中,性能优化是提升用户体验的关键因素之一,本文将介绍如何使用Playwright构建一个自动化性能测试工具,希望... 目录引言工具概述整体架构核心实现解析1. 浏览器初始化2. 性能数据收集3. 资源分析4. 关键性能指

使用Python开发一个Ditto剪贴板数据导出工具

《使用Python开发一个Ditto剪贴板数据导出工具》在日常工作中,我们经常需要处理大量的剪贴板数据,下面将介绍如何使用Python的wxPython库开发一个图形化工具,实现从Ditto数据库中读... 目录前言运行结果项目需求分析技术选型核心功能实现1. Ditto数据库结构分析2. 数据库自动定位3

shell脚本批量导出redis key-value方式

《shell脚本批量导出rediskey-value方式》为避免keys全量扫描导致Redis卡顿,可先通过dump.rdb备份文件在本地恢复,再使用scan命令渐进导出key-value,通过CN... 目录1 背景2 详细步骤2.1 本地docker启动Redis2.2 shell批量导出脚本3 附录总

Android Paging 分页加载库使用实践

《AndroidPaging分页加载库使用实践》AndroidPaging库是Jetpack组件的一部分,它提供了一套完整的解决方案来处理大型数据集的分页加载,本文将深入探讨Paging库... 目录前言一、Paging 库概述二、Paging 3 核心组件1. PagingSource2. Pager3.

Python进行JSON和Excel文件转换处理指南

《Python进行JSON和Excel文件转换处理指南》在数据交换与系统集成中,JSON与Excel是两种极为常见的数据格式,本文将介绍如何使用Python实现将JSON转换为格式化的Excel文件,... 目录将 jsON 导入为格式化 Excel将 Excel 导出为结构化 JSON处理嵌套 JSON:

java中pdf模版填充表单踩坑实战记录(itextPdf、openPdf、pdfbox)

《java中pdf模版填充表单踩坑实战记录(itextPdf、openPdf、pdfbox)》:本文主要介绍java中pdf模版填充表单踩坑的相关资料,OpenPDF、iText、PDFBox是三... 目录准备Pdf模版方法1:itextpdf7填充表单(1)加入依赖(2)代码(3)遇到的问题方法2:pd

Python操作PDF文档的主流库使用指南

《Python操作PDF文档的主流库使用指南》PDF因其跨平台、格式固定的特性成为文档交换的标准,然而,由于其复杂的内部结构,程序化操作PDF一直是个挑战,本文主要为大家整理了Python操作PD... 目录一、 基础操作1.PyPDF2 (及其继任者 pypdf)2.PyMuPDF / fitz3.Fre