本文摘自PHP中文网,作者不言,侵删。
本篇文章给大家带来的内容是关于前端JavaScript写Excel的代码示例,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。前端如何才能写excel,其实也是比较简单的,只是没有接触这一块,当然这边讲的只是简单的入门。
这边主要讲述2种方式,一种是支持主流浏览器,一种是支持Ie浏览器
主流浏览器
这边主要是使用data协议,通过data协议解析excel的Contenttype(application/vnd.ms-excel)
所以这边格式就是 ‘data:+Content-type;+内容’
excel的内容格式是有模版的如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | <html
xmlns:o= "urn:schemas-microsoft-com:office:office"
xmlns:x= "urn:schemas-microsoft-com:office:excel"
xmlns= "http://www.w3.org/TR/REC-html40" >
<head>
<meta charset= "UTF-8" ><!--[ if gte mso 9]>
<xml>
<x:ExcelWorkbook>
<x:ExcelWorksheets>
<x:ExcelWorksheet>
<x:Name>sheet</x:Name>
<x:WorksheetOptions>
<x:DisplayGridlines/>
</x:WorksheetOptions>
</x:ExcelWorksheet>
</x:ExcelWorksheets>
</x:ExcelWorkbook></xml>
</head>
<body>
{tableData}
</body>
</html>
|
然后就是就是根据上述模板进行创建即可,以下就是通过这种方式直接导出excel
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | ( function () {
var template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><meta charset="UTF-8"><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>sheet</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml></head><body>{tableData}</body></html>'
var Excel_URL = 'data:application/vnd.ms-excel;base64,'
var Excel = {
ToExcel: function (data) {
var isIe = window.navigator.userAgent.toLocaleUpperCase().indexOf( 'trident' )
if (isIe !== -1) {
this._IEExport(data)
} else {
this._otherExport(data)
}
},
_otherExport: function (data) {
var content = ''
if (typeof data === 'string' ) {
var ele = document.querySelector(data)
content = template.replace( '{tableData}' , ele.outerHTML)
}
var aEle = document.createElement( 'a' )
aEle.href = Excel_URL + window.btoa(unescape(encodeURIComponent(content)))
aEle.download = '测试.xls'
aEle.click()
}
}
window.Excel = Excel
})()
|
IE浏览器
阅读剩余部分
相关阅读 >>
html文档的基本结构由哪三对标签负责组织
html如何空格
html的<abbr>标签
pop()方法怎么用
svg画图功能:svg实现画出一朵花(附代码)
怎么给html添加js
两分钟了解html中a标签的用法
html文本框怎么设置只读
canvas实现动态粒子连线效果(附代码)
html5 canvas实现中奖转盘的实例代码
更多相关阅读请进入《table》频道 >>
人民邮电出版社
本书对 Vue.js 3 技术细节的分析非常可靠,对于需要深入理解 Vue.js 3 的用户会有很大的帮助。——尤雨溪,Vue.js作者
转载请注明出处:木庄网络博客 » 前端JavaScript写Excel的代码示例