先看导出效果是不是各位需要的
里面包含的内容有:页眉、页脚显示,导出默认页面视图模式,页数显示,插入分页
上代码
jquery.wordexport.js:
if (typeof jQuery !== "undefined" && typeof saveAs !== "undefined") {
(function ($) {
$.fn.wordExport = function (exPortData) {
_initData(exPortData);
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++) {
// 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--";
var fileContent = getModelHtml(markup.html(), mhtmlBottom,exPortData);
var blob = new Blob([fileContent], {
type: "application/msword;charset=utf-8"
});
saveAs(blob, exPortData.fileName + exPortData.fileType);
};
function _initData(exPortData) {
exPortData.fileName = typeof(exPortData.fileName) !== 'undefined' ? exPortData.fileName : "jQuery-Word-Export";
exPortData.fileType=typeof (exPortData.fileType)!=="undefined"?exPortData.fileType:".doc";
}
function getModelHtml(mhtml, mhtmlBottom, exPortData) {
var styles,updateStyles,header,footer="";
if(exPortData.styles){
styles=exPortData.styles.html();
}
if(exPortData.updateExportCss){
updateStyles=exPortData.updateExportCss.html();
}
if(exPortData.isHeader){
header="<div style=\"mso-element:header;padding-bottom:20px;\" id=\"h1\">\n" +
"<p class=\"MsoHeader\">"+exPortData.header+"</p>\n" +
"</div>";
}
if(exPortData.isFooter){
footer="<div style=\"mso-element:footer;text-align: center;\" id=\"f1\">\n" +
"<p class=\"MsoHeader\">"+exPortData.footer+"</p>\n" +
"<p class=\"MsoNum\"><span class=\"num\" style=\"mso-field-code: PAGE \"></span>/<span style=\"mso-field-code:NUMPAGES\"></span>\n</p>\n" +
"</div>";
}
/*
html标签中,和meta标签下面的判断,用来默认显示页面视图模式
*/
return `
<!DOCTYPE html>
<html xmlns:v=\"urn:schemas-microsoft-com:vml\" xmlns:o=\"urn:schemas-microsoft-com:office:office\" xmlns:w=\"urn:schemas-microsoft-com:office:word\" xmlns:m=\"http://schemas.microsoft.com/office/2004/12/omml\" xmlns=\"http://www.w3.org/TR/REC-html40\">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<!--[if gte mso 9]><xml><w:WordDocument><w:View>Print</w:View><w:TrackMoves>false</w:TrackMoves><w:TrackFormatting/><w:ValidateAgainstSchemas/><w:SaveIfXMLInvalid>false</w:SaveIfXMLInvalid><w:IgnoreMixedContent>false</w:IgnoreMixedContent><w:AlwaysShowPlaceholderText>false</w:AlwaysShowPlaceholderText><w:DoNotPromoteQF/><w:LidThemeOther>EN-US</w:LidThemeOther><w:LidThemeAsian>ZH-CN</w:LidThemeAsian><w:LidThemeComplexScript>X-NONE</w:LidThemeComplexScript><w:Compatibility><w:BreakWrappedTables/><w:SnapToGridInCell/><w:WrapTextWithPunct/><w:UseAsianBreakRules/><w:DontGrowAutofit/><w:SplitPgBreakAndParaMark/><w:DontVertAlignCellWithSp/><w:DontBreakConstrainedForcedTables/><w:DontVertAlignInTxbx/><w:Word11KerningPairs/><w:CachedColBalance/><w:UseFELayout/></w:Compatibility><w:BrowserLevel>MicrosoftInternetExplorer4</w:BrowserLevel><m:mathPr><m:mathFont m:val=\"Cambria Math\"/><m:brkBin m:val=\"before\"/><m:brkBinSub m:val=\"--\"/><m:smallFrac m:val=\"off\"/><m:dispDef/><m:lMargin m:val=\"0\"/> <m:rMargin m:val=\"0\"/><m:defJc m:val=\"centerGroup\"/><m:wrapIndent m:val=\"1440\"/><m:intLim m:val=\"subSup\"/><m:naryLim m:val=\"undOvr\"/></m:mathPr></w:WordDocument></xml><![endif]-->
<style type="text/css">
table#hrdftrtbl {
width: 1px;
height: 1px;
overflow: hidden;
}
p.MsoHeader {
font-size: 20px;
font-weight: bold;
text-align: center;
}
p.MsoFooter, li.MsoFooter, div.MsoFooter {
margin: 0in;
mso-pagination: widow-orphan;
tab-stops: center 3.0in right 6.0in;
font-size: 20pt;
font-weight: bold
}
p.MsoNum{
text-align: center;
}
<!-- /*FontDefinitions*/
@page WordSection {
mso-title-page:yes; //首页不显示页眉页脚
mso-page-numbers:0; //起始页码从0开始
mso-header-margin: 20px;
mso-footer-margin: 20px;
mso-header: h1;
mso-footer: f1;
}
div.WordSection {
page: WordSection;
}
-->
${styles}
${updateStyles}
</style>
</head>
<body lang=ZH-CN style="tab-interval:21.0pt">
<div class="WordSection">
${mhtml}
<table id="hrdftrtbl" border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td>
${header}
</td>
<td>
${footer}
</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
${mhtmlBottom}
`}})(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)");
}
}
FileSaver.js
/* FileSaver.js
* A saveAs() FileSaver implementation.
* 1.3.2
* 2016-06-16 18:25:19
*
* By Eli Grey, http://eligrey.com
* License: MIT
* See https://github.com/eligrey/FileSaver.js/blob/master/LICENSE.md
*/
/*global self */
/*jslint bitwise: true, indent: 4, laxbreak: true, laxcomma: true, smarttabs: true, plusplus: true */
/*! @source http://purl.eligrey.com/github/FileSaver.js/blob/master/FileSaver.js */
var saveAs = saveAs || (function (view) {
"use strict";
// IE <10 is explicitly unsupported
if (typeof view === "undefined" || typeof navigator !== "undefined" && /MSIE [1-9]\./.test(navigator.userAgent)) {
return;
}
var
doc = view.document
// only get URL when necessary in case Blob.js hasn't overridden it yet
, get_URL = function () {
return view.URL || view.webkitURL || view;
}
, save_link = doc.createElementNS("http://www.w3.org/1999/xhtml", "a")
, can_use_save_link = "download" in save_link
, click = function (node) {
var event = new MouseEvent("click");
node.dispatchEvent(event);
}
, is_safari = /constructor/i.test(view.HTMLElement)
, is_chrome_ios = /CriOS\/[\d]+/.test(navigator.userAgent)
, throw_outside = function (ex) {
(view.setImmediate || view.setTimeout)(function () {
throw ex;
}, 0);
}
, force_saveable_type = "application/octet-stream"
// the Blob API is fundamentally broken as there is no "downloadfinished" event to subscribe to
, arbitrary_revoke_timeout = 1000 * 40 // in ms
, revoke = function (file) {
var revoker = function () {
if (typeof file === "string") { // file is an object URL
get_URL().revokeObjectURL(file);
} else { // file is a File
file.remove();
}
};
setTimeout(revoker, arbitrary_revoke_timeout);
}
, dispatch = function (filesaver, event_types, event) {
event_types = [].concat(event_types);
var i = event_types.length;
while (i--) {
var listener = filesaver["on" + event_types[i]];
if (typeof listener === "function") {
try {
listener.call(filesaver, event || filesaver);
} catch (ex) {
throw_outside(ex);
}
}
}
}
, auto_bom = function (blob) {
// prepend BOM for UTF-8 XML and text/* types (including HTML)
// note: your browser will automatically convert UTF-16 U+FEFF to EF BB BF
if (/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(blob.type)) {
return new Blob([String.fromCharCode(0xFEFF), blob], {type: blob.type});
}
return blob;
}
, FileSaver = function (blob, name, no_auto_bom) {
if (!no_auto_bom) {
blob = auto_bom(blob);
}
// First try a.download, then web filesystem, then object URLs
var
filesaver = this
, type = blob.type
, force = type === force_saveable_type
, object_url
, dispatch_all = function () {
dispatch(filesaver, "writestart progress write writeend".split(" "));
}
// on any filesys errors revert to saving with object URLs
, fs_error = function () {
if ((is_chrome_ios || (force && is_safari)) && view.FileReader) {
// Safari doesn't allow downloading of blob urls
var reader = new FileReader();
reader.onloadend = function () {
var url = is_chrome_ios ? reader.result : reader.result.replace(/^data:[^;]*;/, 'data:attachment/file;');
var popup = view.open(url, '_blank');
if (!popup) view.location.href = url;
url = undefined; // release reference before dispatching
filesaver.readyState = filesaver.DONE;
dispatch_all();
};
reader.readAsDataURL(blob);
filesaver.readyState = filesaver.INIT;
return;
}
// don't create more object URLs than needed
if (!object_url) {
object_url = get_URL().createObjectURL(blob);
}
if (force) {
view.location.href = object_url;
} else {
var opened = view.open(object_url, "_blank");
if (!opened) {
// Apple does not allow window.open, see https://developer.apple.com/library/safari/documentation/Tools/Conceptual/SafariExtensionGuide/WorkingwithWindowsandTabs/WorkingwithWindowsandTabs.html
view.location.href = object_url;
}
}
filesaver.readyState = filesaver.DONE;
dispatch_all();
revoke(object_url);
}
;
filesaver.readyState = filesaver.INIT;
if (can_use_save_link) {
object_url = get_URL().createObjectURL(blob);
setTimeout(function () {
save_link.href = object_url;
save_link.download = name;
click(save_link);
dispatch_all();
revoke(object_url);
filesaver.readyState = filesaver.DONE;
});
return;
}
fs_error();
}
, FS_proto = FileSaver.prototype
, saveAs = function (blob, name, no_auto_bom) {
return new FileSaver(blob, name || blob.name || "download", no_auto_bom);
}
;
// IE 10+ (native saveAs)
if (typeof navigator !== "undefined" && navigator.msSaveOrOpenBlob) {
return function (blob, name, no_auto_bom) {
name = name || blob.name || "download";
if (!no_auto_bom) {
blob = auto_bom(blob);
}
return navigator.msSaveOrOpenBlob(blob, name);
};
}
FS_proto.abort = function () {
};
FS_proto.readyState = FS_proto.INIT = 0;
FS_proto.WRITING = 1;
FS_proto.DONE = 2;
FS_proto.error =
FS_proto.onwritestart =
FS_proto.onprogress =
FS_proto.onwrite =
FS_proto.onabort =
FS_proto.onerror =
FS_proto.onwriteend =
null;
return saveAs;
}(
typeof self !== "undefined" && self
|| typeof window !== "undefined" && window
|| this.content
));
// `self` is undefined in Firefox for Android content script context
// while `this` is nsIContentFrameMessageManager
// with an attribute `content` that corresponds to the window
if (typeof module !== "undefined" && module.exports) {
module.exports.saveAs = saveAs;
} else if ((typeof define !== "undefined" && define !== null) && (define.amd !== null)) {
define([], function () {
return saveAs;
});
}
使用方法:页面引入jquery.wordexport.js、FileSaver.js、jQuery
页面:
<div class="btn">导出world</div>
<div id="demo" style="padding: 0 30%;">
<h1 style="text-align: center;margin-left: 100px;">测试导出word</h1>
<h1>这是第一行</h1>
<h1 style="page-break-before:always">这是第二行</h1>
<h6>这是第三行</h6>
<p style="text-align: center;page-break-before:always">这是第一行</p>
<p style="text-align: center;">这是第二行</p>
<p style="text-align: center;">这是第三行</p>
</div>
调用方法很简单
let data = {
fileName: "测试word",//文档名
fileType: ".doc",//文档类型 经测试 可以doc xls html 其他的自己去试
isHeader:true,//是否显示页眉 *xls 不要设置页眉页脚 改为false
isFooter:true,//是否显示页脚 *xls 不要设置页眉页脚 改为false
header: '测试页眉',//页眉标题
footer:'测试页脚',//页脚标题
// styles: $("#reportWrap"),//要导出的内容style
// updateExportCss:$("#updateExportCss")//需要修改导出的word样式 宽度高度 margin之类的
}
$(".btn").click(function(){
$("#demo").wordExport(data);
})
重点是这个page-break-before:always,我们项目用的是vue,在vue里面用这个属性会转换成break-before:page,所以分页一直不成功,搞了好久,在网上看别人都说可以,突然想到在html里试一试,果然可以,目前不知道什么原因
jquery.wordexport.js里的代码是别人在里面做的二次开发,地址:https://www.jq22.com/jquery-info23096
最后,前端导出word网上普遍就三种,1、docxtemplater(这个很好用,写好模板,变量替换内容就行了,但是,只能做一般的文本插入,从导出图片开始就要收费了);2、html2canvas + jspdf(这个我个人轻度试用了一下,感觉问题蛮多的);3、就是本文所说的jquery.wordexport.js(依赖于jQuery)