【JS】将表格数据下载为 .csv 文件

文章目录

代码实现

1. 将表格数据转换为字符串格式
2. 字符串格式里面的,逗号表示换列
3. 字符串格式里面的\n符号表示换行
  • 实现
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<button type="button" id="button"> 下载文件</button>
	</body>
	<script type="text/javascript">
		const titleTable = ['A', 'B', 'C', 'D'];
		const dataTable = [{
      
      
			a: 1,
			b: 2,
			c: 3,
			d: 4,
			e: 5,
		}, {
      
      
			a: 1,
			b: 2,
			c: 3,
			d: 4,
			e: 5,
		}]

		function onDownload() {
      
      
			const data = `${ 
        dataTable
					          .map((item) => [item.a, item.b, item.c, item.d].toString())
					          .join('\n')}\n`;
			const title = `${ 
        titleTable.toString()}\n`;
			// encodeURIComponent 解决中文乱码
			const url = `data:text/csv;charset=utf-8,\ufeff${ 
        encodeURIComponent(`${ 
          title}${ 
          data}`)}`;
			// 创建a标签
			const link = document.createElement('a');
			link.href = url;
			link.download = 'test.csv';
			link.click();
		}
		// 获取按钮
		const button = document.getElementById('button')
		// 给按钮添加点击事件
		button.onclick =onDownload()
	</script>
</html>

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_45677671/article/details/131509671