将vue页面文本导出到word,并设置页眉页脚,分页打印相关讲解--高级版

此博客介绍了如何使用Vue和docx.js库创建一个导出Word的功能,内容包括设置页眉页脚、页码、时间戳,确保每个明细占一页且无空白页。通过代码展示了如何在打印和导出时添加页眉、页脚和分页,以及时间的格式化和加粗处理。
摘要由CSDN通过智能技术生成

需求:

将以下内容导出到word,并设置页眉页脚,页码以及导出时间,且时间、页码加粗处理;每一个明细各占一页,且不能有空白页出现。

在这里插入图片描述

最终效果展示:

在这里插入图片描述

代码展示及讲解:

<template>
    <div>
        
        <hr />
            <div class="s-header">               
                <img src="../../assets/logo.png" alt />                                
                <span>信息列表</span>                
                <button @click="print">打印</button>
                <button @click="exportWord">导出到word</button>
                <span>&nbsp;</span>
            </div>
        <hr />


    <div class="word">
        <!--startprint-->
        <div v-for="(item, index) in DataList" :key="index" style="margin:25px;">
        <div style="text-align:center; height:28px;"><span>商检编号:</span><span>{{item.new_opportunitiesforbatchnumber}}</span></div>   
        <div style="height:28px;"><span>MODEL(车型):</span><span>{{item.new_modelstodescribe}}</span></div>
        <div style="height:28px;"><span>SERIAL NO(车工号):</span><span>{{item.new_thevehiclefile_id}}</span></div>
        <div style="height:28px;"><span>VIN NO(VIN号):</span><span>{{item.new_vinnumber}}</span></div>       
        <div style="height:28px;"><span>SIZE(长*宽*高):</span><span>{{parseFloat(item.new_long)}}*{{parseFloat(item.new_wide)}}*{{parseFloat(item.new_high)}}</span></div>               
        <!-- 打印时分页处理 加上这段代码即可:page-break-after:always-->
        <div style="height:28px; page-break-after:always"><span>SGIPPING MARK(唛头信息):</span><span>{{item.new_mark}}</span></div>      
        </div>
        <!--endprint-->
    </div>
    </div>
</template>

<script>
import { saveAs } from './FileSaver'
import * as docx from './index'
export default {
    data(){
        return{          
            DataList:[
                {
                    new_opportunitiesforbatchnumber : "0",
                    new_modelstodescribe: "GR3423467",
                    new_thevehiclefile_id:"KH4666",
                    new_vinnumber:"GRT6798398",
                    new_long:"12.5",
                    new_wide:"7.93",
                    new_high:"5.3",
                    new_mark:"M/V"
                },
                {
                    new_opportunitiesforbatchnumber : "1",
                    new_modelstodescribe: "ZK09GGH04",
                    new_thevehiclefile_id:"SDFE234",
                    new_vinnumber:"JYWE458795",
                    new_long:"13.7",
                    new_wide:"7.1",
                    new_high:"4.2",
                    new_mark:"N/M"
                },                            
            ]
        };
    },
    mounted() {},
    methods: {       
        //打印
        print(){  
            $(".word").printArea();                 
        },
        //时间格式处理
        formatter (thistime, fmt) {
			let $this = new Date(thistime)
			let o = {
				'M+': $this.getMonth() + 1,
				'd+': $this.getDate(),
				'h+': $this.getHours(),
				'm+': $this.getMinutes(),
				's+': $this.getSeconds(),
				'q+': Math.floor(($this.getMonth() + 3) / 3),
				'S': $this.getMilliseconds()
			}
			if (/(y+)/.test(fmt)) {
				fmt = fmt.replace(RegExp.$1, ($this.getFullYear() + '').substr(4 - RegExp.$1.length))
			}
			for (var k in o) {
				if (new RegExp('(' + k + ')').test(fmt)) {
				fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
				}
			}
			return fmt
		},
        //导出到word--重点
		async exportWord() {
			const doc = new docx.Document()	
			//for和下面的if语句是对分页的一种处理办法,防止有空白页出现		
			for	(let i = 0; i < this.DataList.length; i ++) {
				var paragraph = {
						children: [
							new docx.TextRun({
								text: 'SGIPPING MARK(唛头信息):'+this.DataList[i].new_mark,
								bold: true,
								size: 28,
								font: {
									name: 'Times New Roman',
								},								
							}),														
						],
					};                               
				if (i != this.DataList.length - 1){//最后一个不加分页
					paragraph.children.push(new docx.PageBreak()); 
				}
				//如若想要第二页起用新的页眉和页脚,紧跟doc.addSection()后再写一段doc.addSection()方法即可!
				doc.addSection({
				headers: {
					default: new docx.Header({  //页眉
						children: [
							new docx.Paragraph({
								//alignment: docx.AlignmentType.CENTER,  //居中
								children: [
									new docx.TextRun({
										text: this.formatter(new Date(), 'yyyy/M/d'),										
										font: {
											name: 'Microdoft YaHei',  //字体设置
										},
                                        bold:true,  //字体加粗
										size: 18,  //字号设置
									}),
									new docx.TextRun({
									text: '         一个不想被猫吃的鱼', //段落文本										
										font: {
											name: 'Times New Roman', //字体设置
										},
										size: 18,
									}),
								],
							}),
						],
					}),
				},
				footers: {//页脚
					default: new docx.Footer({
						children: [
                            new docx.Paragraph({
								//alignment: docx.AlignmentType.CENTER,//居中对齐
								children: [
									new docx.TextRun({                                        
										text: '一个不喜欢吃鱼的猫'+'                           ',										
										font: {
											name: 'Times New Roman',
										},                                      
										size: 18,
									}),
									new docx.TextRun({
									    text: (i+1)+'/'+this.DataList.length,	//简单的做一下页码标记,但显然不能这么做									
										font: {
											name: 'Times New Roman',                                           
										},                                       
                                        bold: true,
										size: 20,
									}),
								],
							})
                        ],
					}),
				},
				margins: {},
				size: 30,
				properties: {},
				children: [	 
                    new docx.Paragraph({
						alignment: docx.AlignmentType.CENTER,//居中
						children: [
							new docx.TextRun({
								text: '商检编号:',	
								bold: true,
								size: 28,
								font: {
									name: 'Times New Roman',
								},							
							}),
							new docx.TextRun({
								text: this.DataList[i].new_opportunitiesforbatchnumber,
								bold: true,
								size: 28,
								font: {
									name: 'Times New Roman',
								},								
							}),							
						],
					}),  
                    //段落设置,一个段落即一个“new docx.Paragraph()”,相当于换行符               									
					new docx.Paragraph({
						children: [
                            //如果对text里面的文本内容有严格的字体、字号、加粗等格式要求,可再写一个new docx.TextRun()方法使其独立出来,单独处理,text里面的内容会自动作字符串拼接处理
							new docx.TextRun({
								text: 'MODEL(车型):'+this.DataList[i].new_modelstodescribe,
								bold: true,
								size: 28,
								font: {
									name: 'Times New Roman',
								},								
							}),	
                            // new docx.TextRun({
							// 	text: this.DataList[i].new_modelstodescribe,
							// 	bold: true,
							// 	size: 32,
							// 	font: {
							// 		name: 'Microdoft YaHei',  //微软雅黑
							// 	},								
							// }),																			
						],
					}),
					new docx.Paragraph({
						children: [
							new docx.TextRun({
								text: 'SERIAL NO(车工号):'+this.DataList[i].new_thevehiclefile_id,
								bold: true,
								size: 28,
								font: {
									name: 'Times New Roman',
								},								
							}),																			
						],
					}),
					new docx.Paragraph({
						children: [
							new docx.TextRun({
								text: 'VIN NO(VIN号):'+this.DataList[i].new_vinnumber,
								bold: true,
								size: 28,
								font: {
									name: 'Times New Roman',
								},								
							}),																			
						],
					}),					
					new docx.Paragraph({
						children: [
							new docx.TextRun({
								text: 'SIZE(长*宽*高):'+parseFloat(this.DataList[i].new_long)+'*'+parseFloat(this.DataList[i].new_wide)+'*'+parseFloat(this.DataList[i].new_high),
								bold: true,
								size: 28,
								font: {
									name: 'Times New Roman',
								},								
							}),																				
						],
					}),										
                    //分页方法:new docx.PageBreak()
                    //因为最后一段内容之后要插入分页符,所以在开头部分已做相关处理
					new docx.Paragraph(paragraph),
				],
			    })
			}			

			docx.Packer.toBlob(doc).then((blob) => {
				saveAs(blob, '导出测试.docx');	//最后一个参数为:导出文件名,可自定义			
			})
		},    
    },
}
</script>
<style lang="less" scoped>
.s-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 30px;
  img{   
    margin-left: 20px;  
    width: 20px;
    height: 20px;
  }
}
.s-header-a {
    display: flex;
    flex-direction: row;
    align-items: center;
    height: 30px;
    img{  
        width: 20px;
        height: 20px;
    }
    span{
        margin-left: 5px;
    }
}
.s-header-b {
    display: flex;
    flex-direction: row;
    align-items: center;
    height: 30px;
    img{ 
        margin-left: 10px; 
        width: 20px;
        height: 20px;
    }
    span{
        margin-left: 5px;
    }
}

</style>

对上述代码作一下简化处理:

function a(){
		//文本设置
		new docx.TextRun({
         text: '自定义文本',										
          font: {
            name: 'Microdoft YaHei',  //字体设置
          },
          bold:true,  //字体加粗
          size: 18,  //字号设置
        }),	
        
		//整体内容结构,需要引入index.js文件                
		const doc = new docx.Document()			
		doc.addSection({
          headers: {
            default: new docx.Header({  //页眉
              children: [
                new docx.Paragraph({
                  alignment: docx.AlignmentType.CENTER,  //居中
                  children: [
                    new docx.TextRun(....),								
                  ],
                }),
              ],
            }),
          },
          footers: {//页脚
            default: new docx.Footer({
              children: [
                  new docx.Paragraph({								
                  children: [
                    new docx.TextRun(....),									
                  ],
                })
              ],
            }),
          },
          margins: {},
          size: 30,
          properties: {},
          children: [	 
            new docx.Paragraph({  //段落,即回车符
              alignment: docx.AlignmentType.CENTER,//居中
              children: [
                new docx.TextRun(....), //文本
                new docx.TextRun(....),
                ......
              ],
              new docx.PageBreak(),  //另起一页,即插入分页符
            }),
            new docx.Paragraph(....),  //第二段
            new docx.Paragraph(....),   //第三段
            ....          
          ]
          }); 
        //导出word方法,需引入FileSaver.js文件
        docx.Packer.toBlob(doc).then((blob) => {
				saveAs(blob, '导出测试.docx');	//最后一个参数为:导出文件名,可自定义			
		}); 
}

在index.html做一个全局引用

<!DOCTYPE html>
<html lang="">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <!-- ....其他引用.... -->
    
    <!-- 导出到word引用js -->
    <script src="./js/FileSaver.js"></script>
    <script src="./js/index.js"></script>
    
    <!-- 局部打印引用js -->
    <script src="./js/jquery-3.5.1.min.js"></script>
    <script src="./js/jquery.PrintArea.js"></script>
  </head>
  <body>
    <div id="app"></div>
    <!-- built files will be auto injected -->
  </body>
</html>

需要引用的js

index.js、FileSaver.js文件下载地址:

转到仓库下载源码

如有疑问可留言。

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值