xlsx结合file-saver实现纯前端导出excel

1.下载xlsx和file-saver, 并引用

 npm install xlsx -s
 npm install file-saver  -s
import XLSX from 'xlsx';
import FileSaver from 'file-saver'
  1. 导出方法
	exportExcel(){
			// 判断要导出的节点中是否有fixed的表格,如果有,转换excel时先将该dom移除,然后append回去,
			let wb;
			
			this.$nextTick(() => {
				// 导出的内容只做解析,不进行格式转换
				let xlsxParam = { raw: true }; 
				wb = XLSX.utils.table_to_book(document.querySelector("#detailTable"), xlsxParam);
				
				//若需要自定义格式转换,则使用下面方法
				/*wb = XLSX.utils.table_to_book(document.querySelector("#detailTable"))
				for(let obj in wb.Sheets.Sheet1){
					if(wb.Sheets.Sheet1[obj].z === 'm/d/yy'){//时间格式
						wb.Sheets.Sheet1[obj].v = this.formatDate(wb.Sheets.Sheet1[obj].v, '-')
					}
				}*/
				const wbout = XLSX.write(wb, {
					bookType: "xlsx",
					bookSST: false,
					type: "array"
				});
				try {
					FileSaver.saveAs(
						new Blob([wbout], {
							type: "application/octet-stream"
						}),
						this.excelName+'.xlsx'
					);
				} catch (e) {
					if (typeof console !== "undefined") console.log(e, wbout);
				}
				return wbout;
			});
		},
	//excel读取2018/01/01这种时间格式是会将它装换成数字类似于46254.1545151415 
	// numb是传过来的整数数字,format是之间间隔的符号
	formatDate(numb, format) {
			const time = new Date((numb - 1) * 24 * 3600000 + 1)
			time.setYear(time.getFullYear() - 70)
			const year = time.getFullYear() + ''
			const month = time.getMonth() + 1 + ''
			const date = time.getDate() - 1 + ''
			if (format && format.length === 1) {
				return year + format + (month < 10 ? '0' + month : month) + format + (date < 10 ? '0' + date : date)
			}
			return year + (month < 10 ? '0' + month : month) + (date < 10 ? '0' + date : date)
		}

参考地址: https://blog.csdn.net/dwb123456123456/article/details/85012735

你可能感兴趣的:(vue,vue.js,javascript)