根据项目需求,主要用的layui这个前段框架,现在需要支持将页面下载为四种格式的文件。
Excel、CSV
第一步:去layUi官网中找到对应的扩展文档;
下载对应的扩展文件,导入项目中。
根据文档的写法。初始化Excel控件
layui.config({
base: 'layui_exts/', // 配置一个可访问地址
}).extend({
excel: 'excel',
});
layui.use(['excel'], function (){
//导出格式在这里改变类型就行了
//layui.excel.exportExcel([[1, 2, 3]], '表格导出.xlsx', 'xlsx')
layui.excel.exportExcel([[1, 2, 3]], '表格导出.csv', 'csv')
})
文档官方地址:
http://excel.wj2015.com/_book/
页面:
下载的Excel效果:
下载的CSV效果:
Word
第一步:导入js文件
<script type="text/javascript" src="../layui/layui.js"></script>
<script type="text/javascript" src="../extend/FileSaver.js"></script>
<script type="text/javascript" src="../extend/wordexport.js"></script>
FileSaver.js代码:
/*
* FileSaver.js
* A saveAs() FileSaver implementation.
*
* By Eli Grey, http://eligrey.com
*
* License : https://github.com/eligrey/FileSaver.js/blob/master/LICENSE.md (MIT)
* source : http://purl.eligrey.com/github/FileSaver.js
*/
// The one and only way of getting global scope in all environments
// https://stackoverflow.com/q/3277182/1008999
layui.define(["jquery"], function (exports) {
var jQuery = layui.jquery;
var obj = (function($) {
var _global = typeof window === 'object' && window.window === window
? window : typeof self === 'object' && self.self === self
? self : typeof global === 'object' && global.global === global
? global
: this
function bom (blob, opts) {
if (typeof opts === 'undefined') opts = { autoBom: false }
else if (typeof opts !== 'object') {
console.warn('Deprecated: Expected third argument to be a object')
opts = { autoBom: !opts }
}
// 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 (opts.autoBom && /^\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
}
function download (url, name, opts) {
var xhr = new XMLHttpRequest()
xhr.open('GET', url)
xhr.responseType = 'blob'
xhr.onload = function () {
saveAs(xhr.response, name, opts)
}
xhr.onerror = function () {
console.error('could not download file')
}
xhr.send()
}
function corsEnabled (url) {
var xhr = new XMLHttpRequest()
// use sync to avoid popup blocker
xhr.open('HEAD', url, false)
try {
xhr.send()
} catch (e) {}
return xhr.status >= 200 && xhr.status <&#