Exporting to H5 page form data to a local file, export to local csv file

Export table reference iview

  1. Export Table header data and the need for specific data
//表头
let columns = [
	{ title: '品牌', key: 'brandName' },
	{ title: '品种', key: 'breedName' },
	{ title: '平均零售价', key: 'avgRetailPrice' },
	{ title: '平均批发价', key: 'avgBatchPrice' },
	{ title: '平均成本价', key: 'avgCostPrice' },
	{ title: '预估折扣', key: 'discount' },
	{ title: '加盟分成', key: 'franchiseeSharing' },
	{ title: '总部毛利率', key: 'headquartersRossInterestRate' },
	{ title: '加盟分成金额', key: 'franchiseeSharingAmount' },
	{ title: '总部分成金额', key: 'headquartersSharingAmount' },
	{ title: '总部分成利润', key: 'headquartersProfits' },
	{ title: '总部分成', key: 'headquartersSharing' },
];
//数据源
let datas = [
	{
       "franchiseeSharing": 0,
       "brandName": "安姿",
       "avgCostPrice": 36.1,
       "discount": 1,
       "headquartersRossInterestRate": 0.9118,
       "categoryName": "太阳镜",
       "avgBatchPrice": 44.81,
       "headquartersSharing": 1,
       "headquartersProfits": 373.25,
       "avgRetailPrice": 409.35,
       "headquartersSharingAmount": 409.35,
       "franchiseeSharingAmount": 0
   },
   {
       "franchiseeSharing": 0,
       "brandName": "安姿",
       "avgCostPrice": 36.1,
       "discount": 0.9,
       "headquartersRossInterestRate": 0.902,
       "categoryName": "太阳镜",
       "avgBatchPrice": 44.81,
       "headquartersSharing": 1,
       "headquartersProfits": 332.32,
       "avgRetailPrice": 409.35,
       "headquartersSharingAmount": 368.42,
       "franchiseeSharingAmount": 0
   },
]
  1. Converts the data format
    used between each column '' is connected, header and source data for each row by '\ r \ n' is connected
//columns: 表头
//datas: 数据源
csv(columns, datas, options) {
	let defaults = {
		separator: ',',
		quoted: false
	}, newLine = '\r\n';
	options = Object.assign({}, defaults,options);

	let columnOrder;
	//content 存放表头, 数据源用逗号连接后的字符串,
	//column: 存放当前表头
	const content = [], column = [];
	//columnOrder:存放需要导出的datas数据项对应的key
	columnOrder = columns.map(v => {
		column.push(v.title) //表头项里没有设置title属性,可以用v.key代替
		return v.key
	})
	//把表头列名用逗号连接,存入content
	appendLine(content, column, options)
	// 把datas里跟表头列key相符的数据拼接起来
	if (Array.isArray(datas)) {
		datas.forEach(row => {
			if (!Array.isArray(row)) {
				row = columnOrder.map(k => row[k])
			}
			appendLine(content, row, options)
		})
	}
	//拼接方法
	function appendLine(content, row, { separator, quoted }) {
		const line = row.map(data => {
			return data
		})
		content.push(line.join(separator))
	}
	//用换行符连接
	return content.join(newLine)
},
  1. Export
exportCsv() {
	function has(browser) {
	//判断浏览器,做兼容处理
		const ua = window.navigator.userAgent;
		//是否是IE浏览器
		if (browser === 'ie') {
			const isIE = ua.indexOf('compatible') > -1 && ua.indexOf('MSIE') > -1;
			if (isIE) {
				const reIE = new RegExp('MSIE (\\d+\\.\\d+)');
				reIE.test(us);
				return parseFloat(RegExp['$1'])
			} else {
				return false
			}
		} else {
			return ua.indexOf(browser) > -1
		}
	}
	const csv = {
		_isIE11() {
			let iev = 0;
			const ieold = (/MSIE (\d+\.\d+);/.test(navigator.userAgent));
			const trident = !!navigator.userAgent.match(/Trident\/7.0/);
			const rv = navigator.userAgent.indexOf('rv:11.0');

			if (ieold) {
				iev = Number(RegExp.$1);
			}
			if (navigator.appVersion.indexOf('MSIE 10') !== -1) {
				iev = 10;
			}
			if (trident && rv !== -1) {
				iev = 11;
			}

			return iev === 11;
		},
		_isEdge() {
			return /Edge/.test(navigator.userAgent);
		},
		_getDownloadUrl(text) {
			const BOM = '\uFEFF'; //表明是字节流的标识,用来标示它是UTF-8的文件。

			if (window.Blob && window.URL && window.URL.createObjectURL) {
				const csvData = new Blob([BOM + text], { type: 'text/csv' });
				return URL.createObjectURL(csvData)
			} else {
				return 'data:attachment/csv;charset=utf-8,' + BOM + encodeURIComponent(text)
			}
		},
		download: function (fileName, text) {
		//IE及IE10以下,通过富文本编辑器的saveas来保存
			if (has('ie') && has('ie') < 10) {
				const oWin = window.top.open('about:blank', '_blank');
				oWin.document.charset = 'utf-8';
				oWin.document.write(text);
				oWin.document.close();
				oWin.document.execCommand('SaveAs',false, fileName);
				oWin.close()
			} else if (has('ie') === 10 || this._isIE11() || this._isEdge()) {
			//navigator.msSaveBlob
				const BOM = '\uFEFF'; //表示utf-8编码的字节流
				const csvData = new Blob([BOM + text], { type: 'text/csv' });
				navigator.msSaveBlob(csvData, fileName);
			} else {
			//通过a标签。模拟下载
				const link = document.createElement('a');
				link.download = fileName;
				link.href = this._getDownloadUrl(text);
				document.body.appendChild(link);
				link.click();
				document.body.removeChild(link);
			}
		}
	};

	return csv;
}
  1. Full use
const params = {
	filename: 'table.csv',
	original: true,
};
let columns = [], datas = []; //数据格式参考1
const data = this.csv(columns, datas, params);
exportCsv().download(params.filename, data);
Published 66 original articles · won praise 13 · views 60000 +

Guess you like

Origin blog.csdn.net/haoyanyu_/article/details/100100054