@travel_wsy/export_word
Version:
导出word格式
93 lines (91 loc) • 2.4 kB
JavaScript
import Docxtemplater from "docxtemplater";
import PizZip from "pizzip";
import JSZipUtils from 'jszip-utils'
import {
saveAs
} from 'file-saver'
const expressions = require('angular-expressions')
/**
* 导出work表格
* @param {Object} data 数据
* @param {String} fileName word 导出文件名
* @param {String} tempPath word 模板路径
*/
export function exportDocx(data, fileName = '', tempPath = '') {
if (validatenull(data)) {
console.log('请上传数据')
return
}
if (validatenull(fileName)) {
console.log('请上传文件名')
return
}
if (validatenull(tempPath)) {
console.log('请上传模板文件路径')
return
}
expressions.filters.lower = (input) => {
if (!input) return input
return input.toLowerCase()
}
JSZipUtils.getBinaryContent(tempPath, (error, content) => {
if (error) {
console.log(error, '压缩')
}
let zip = new PizZip(content)
let docx = new Docxtemplater(zip, {
parser: angularParse
})
docx.setData(data)
try {
docx.render()
} catch (err) {
console.log(err, 'render')
}
let exportOut = docx.getZip().generate({
type: 'blob',
mimeType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
})
saveAs(exportOut, fileName)
})
}
/**
* 处理内容
* @param {*} tag
* @returns
*/
function angularParse(tag) {
tag = tag.replace(/^\.$/, 'this').replace(/(’|‘)/g, "'").replace(/(”|“)/g, '"')
const expr = expressions.compile(tag)
return {
get: function (scope, context) {
let obj = {}
const scopeList = context.scopeList
const num = context.num
for (var i = 0, len = num + 1; i < len; i++) {
obj = Object.assign(obj, scopeList[i])
}
return expr(scope, obj)
}
}
}
/**
* 判断是否为空
*/
function validatenull(val) {
if (typeof val === 'boolean') {
return false
}
if (typeof val === 'number') {
return false
}
if (val instanceof Array) {
if (val.length === 0) return true
} else if (val instanceof Object) {
if (JSON.stringify(val) === '{}') return true
} else {
if (val === 'null' || val == null || val === 'undefined' || val === undefined || val === '') return true
return false
}
return false
}