| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104 |
- import XLSX from 'xlsx'
- /**
- * HTMLtabl转excel文件
- */
- class HtmlTbale2ExcelService {
- /**
- * 导出excel
- * @param {string} fileName 保存文件名
- * @param {HTMLElement} table table表格DOM
- */
- outfile(fileName, table) {
- try {
- const sheet1 = XLSX.utils.table_to_sheet(table, { raw: true })
- const blob2 = this.sheets2book2blob([ sheet1 ])
- this.openDownloadDialog(blob2, `${fileName}.xlsx`)
- } catch (error) {
- console.error('导出错误')
- }
- }
- /**
- * sheet转blob
- * @param {Array<any>} params sheet参数arr|obj
- */
- sheets2book2blob(params) {
- if (params && params.length > 0) {
- const workbook = {
- SheetNames: [],
- Sheets: {}
- }
- // 参数两种模式纯arr || arrobj
- for (let k = 0; k < params.length; k++) {
- const el = params[k]
- if (el.db && el.name) {
- workbook.SheetNames.push(el.name)
- workbook.Sheets[el.name] = el.db
- } else {
- workbook.SheetNames.push(`sheet${k}`)
- workbook.Sheets[`sheet${k}`] = el
- }
- }
- // 生成excel的配置项
- const wopts = {
- bookType: 'xlsx', // 要生成的文件类型
- bookSST: false, // 是否生成Shared String Table,官方解释是,如果开启生成速度会下降,但在低版本IOS设备上有更好的兼容性
- type: 'binary'
- }
- const wbout = XLSX.write(workbook, wopts)
- const blob = new Blob([ this.s2ab(wbout) ], { type: 'application/octet-stream' })
- return blob
- }
- console.error('参数错误(need arr and arr obj)')
- }
- /**
- * 字符串转ArrayBuffer
- * @param {string} s 字符串
- */
- s2ab(s) {
- const buf = new ArrayBuffer(s.length)
- const view = new Uint8Array(buf)
- for (let i = 0; i !== s.length; ++i) view[i] = s.charCodeAt(i) & 0xff
- return buf
- }
- /**
- * 下载
- * @param {any} url 文件blob
- * @param {string} fileName 文件名
- */
- openDownloadDialog(url, fileName) {
- if (typeof url === 'object' && url instanceof Blob) {
- url = URL.createObjectURL(url) // 创建blob地址
- }
- const aLink = document.createElement('a')
- aLink.href = url
- aLink.download = fileName || '' // HTML5新增的属性,指定保存文件名,可以不要后缀,注意,file:///模式下不会生效
- let event
- if (window.MouseEvent) event = new MouseEvent('click')
- else {
- event = document.createEvent('MouseEvents')
- event.initMouseEvent(
- 'click',
- true,
- false,
- window,
- 0,
- 0,
- 0,
- 0,
- 0,
- false,
- false,
- false,
- false,
- 0,
- null
- )
- }
- aLink.dispatchEvent(event)
- }
- }
- export default new HtmlTbale2ExcelService()
|