1. 程式人生 > >js解析Excel檔案,解析後的資料用Echarts折線圖展示

js解析Excel檔案,解析後的資料用Echarts折線圖展示

不多說了,直接上程式碼

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>js解析Excel</title>
		<script type="text/javascript" src="js/jquery-1.10.2.js" ></script>
		<script type="text/javascript" src="js/xlsx.full.min.js"></script>
		<script type="text/javascript" src="js/echarts3.0.js" ></script>
	</head>
	<body>
		<input type="file" id="excel-file" />
		<div id="demo" style="width: 100%; height: 900px;"></div>
	</body>
	<script>
		$('#excel-file').change(function(e){
			var files = e.target.files;
			
			var fileReader = new FileReader();
			fileReader.onload = function(ev){
				try {
					var data = ev.target.result,
						//以二進位制流方式讀取得到整份excel表格物件
						workbook = XLSX.read(data, {type : 'binary'}),
						persons = [];//儲存獲取到的資料
				} catch (e) {
					console.log('檔案型別不正確');
					return;
				}
				
				//表格的表格範圍,可用於判斷表頭數量是否正確
				var fromTo = '';
			
				//遍歷每張表讀取
				for (var sheet in workbook.Sheets) {
					if (workbook.Sheets.hasOwnProperty(sheet)) {
						fromTo = workbook.Sheets[sheet]['!ref'];
						console.log(fromTo);
						persons = persons.concat(XLSX.utils.sheet_to_json(workbook.Sheets[sheet]));
						//break;  //如果只取第一張表,就取消註釋這行
					}
				}
				debugger;
				console.log(persons);
				var chart = echarts.init(document.getElementById('demo'));
                
                var data2 = [];
                for(var i = 0; i < persons.length; i++){
                	var dates = persons[i].date;
                	var datas = persons[i].data;
                	var data1 = [dates, datas];
                	data2.push(data1);
                }
                var dateList = data2.map(function (item) {
				    return item[0];
				});
				var valueList = data2.map(function (item) {
				    return item[1];
				});
				
				
				option = {
				
				    // Make gradient line here
				    visualMap: [{
				        show: false,
				        type: 'continuous',
				        seriesIndex: 0,
				        min: 0,
				        max: 400
				    }],
				
				
				    title: [{
				        left: 'center',
				        text: '折線圖'
				    }],
				    tooltip: {
				        trigger: 'axis'
				    },
				    xAxis: [{
				        data: dateList.sort()
				    }],
				    yAxis: [{
				        splitLine: {show: false}
				    }],
				    grid: [{
				        bottom: '3%',
				        right: '2%',
				        left: '2%',
				        top: '10%'
				    }],
				    series: [{
				        type: 'line',
				        showSymbol: false,
				        data: valueList
				    }]
				};
				chart.setOption(option);
			};
			//以二進位制方式開啟檔案
			fileReader.readAsBinaryString(files[0]);
		});
	</script>
</html>

效果預覽: