饼图生成器的构想

前言

今天分班结果出来了,我在十一班,我们班同学各奔东西。
我在11班
老总在一班
那么如何直观看出同学们都去哪了呢,这就要用到饼图了。

实现方式

要实现一个饼图生成器,可以使用HTML、CSS和JavaScript。使用Chart.js库来创建立体的饼图。用户可以输入数据到表格,实时更新图表,并通过上传Excel文件(.xls或.xlsx)来生成饼状图。
首先,需要在HTML文件中引入Chart.js库:

1
2
3
4
5
6
7
8
9
10
11
12
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Pie Chart Generator</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
<!-- 在这里添加你的代码 -->
</body>
</html>

接下来,添加一个表格和一个按钮,用于输入数据和上传文件:

Label Value
1
2
3
4
5
6
7
8
9
10
11
12
<table id="data-table">
<tr>
<th>Label</th>
<th>Value</th>
</tr>
<tr>
<td><input type="text" class="label"></td>
<td><input type="number" class="value"></td>
</tr>
</table>
<button id="add-row">Add Row</button>
<button id="upload-file">Upload Excel File</button>

然后,添加一个canvas元素,用于显示饼图:

1
<canvas id="pie-chart"></canvas>

接下来,使用JavaScript编写功能,包括添加行、实时更新图表和上传Excel文件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
<script>
// 获取DOM元素
const dataTable = document.getElementById('data-table');
const addRowButton = document.getElementById('add-row');
const uploadFileButton = document.getElementById('upload-file');
const pieChartCanvas = document.getElementById('pie-chart').getContext('2d');

// 初始化图表
const chart = new Chart(pieChartCanvas, {
type: 'pie',
data: {
labels: [],
datasets: [{
data: [],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
animation: {
duration: 500,
easing: 'easeInOutQuart'
}
}
});

// 添加行事件
addRowButton.addEventListener('click', () => {
const newRow = dataTable.insertRow(-1);
const labelCell = newRow.insertCell(0);
const valueCell = newRow.insertCell(1);
labelCell.innerHTML = `<input type="text" class="label">`;
valueCell.innerHTML = `<input type="number" class="value">`;
});

// 实时更新图表事件
dataTable.addEventListener('input', () => {
const labels = Array.from(document.querySelectorAll('.label')).map(input => input.value);
const values = Array.from(document.querySelectorAll('.value')).map(input => parseInt(input.value));
chart.data.labels = labels;
chart.data.datasets[0].data = values;
chart.update();
});

// 上传Excel文件事件(需要安装xlsx库)
uploadFileButton.addEventListener('click', () => {
const fileInput = document.createElement('input');
fileInput.type = 'file';
fileInput.accept = '.xls,.xlsx';
fileInput.onchange = (event) => {
const file = event.target.files[0];
const reader = new FileReader();
reader.onload = (e) => {
const data = new Uint8Array(e.target.result);
const workbook = XLSX.read(data, { type: 'array' });
const sheetName = workbook.SheetNames[0];
const sheet = workbook.Sheets[sheetName];
const jsonData = XLSX.utils.sheet_to_json(sheet, { header: 1 });
const labels = jsonData.slice(1).map(row => row[0]);
const values = jsonData.slice(1).map(row => parseInt(row[1]));
chart.data.labels = labels;
chart.data.datasets[0].data = values;
chart.update();
};
reader.readAsArrayBuffer(file);
};
fileInput.click();
});
</script>

注意:这个示例使用了xlsx库来处理Excel文件,你需要在项目中安装它:

1
npm install xlsx

然后将上述代码中的script标签替换为以下内容:

1
<script src="https://unpkg.com/xlsx/dist/xlsx.full.min.js"></script>

美化思路

但是这样,UI非常丑,功能也非常简陋,没有错误检查,容易报错,需要进一步调整

为了实现一个具有更美观的UI、错误检查以及客户端解析Excel文件的功能,我们需要做几个改进。首先,我们将使用CSS来美化界面,并引入一个JavaScript库,如SheetJS(xlsx.js),来处理文件上传和解析Excel文件。此外,我们还需要添加一些JavaScript代码来验证用户输入。
我采用了分离方式编写。

功能

这一版加入了文件上传功能,允许用户上传.xls或.xlsx文件来生成饼图。当用户上传文件后,loadFile函数会被调用,读取文件内容并将其转换为JSON格式的数据。这些数据随后被用来填充表格,之后用户可以通过点击“从文件生成图表”按钮来更新饼图。
JavaScript脚本(script.js):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
// script.js

// 初始化ECharts实例
var chart = echarts.init(document.getElementById('chart'));

// 更新图表函数
function updateChart() {
var title = document.getElementById('title').value;
var subtitle = document.getElementById('subtitle').value;
var data = [];

// 遍历所有输入行
document.querySelectorAll('#dataRows tr').forEach((row, index) => {
var labelInput = row.querySelector('.labelInput');
var valueInput = row.querySelector('.valueInput');

// 检查是否有空标签或非数字的值
if (labelInput.value.trim() === '' || isNaN(valueInput.value.trim()) || valueInput.value.trim() === '') {
alert("请确保每行都有有效的标签和数值!");
return;
}

// 添加到数据数组
data.push({
name: labelInput.value.trim(),
value: parseFloat(valueInput.value.trim())
});
});

// 设置图表选项
var option = {
tooltip: {},
title: {
text: title,
subtext: subtitle
},
series: [{
type: 'pie',
radius: '55%',
center: ['50%', '60%'],
data: data,
emphasis: {
itemStyle: {
shadowBlur: 10,
shadowOffsetX: 0,
shadowColor: 'rgba(0, 0, 0, 0.5)'
}
}
}]
};

// 更新图表
chart.setOption(option);
}

// 添加行
function addRow() {
var tableBody = document.getElementById('dataRows');
var newRow = document.createElement('tr');
newRow.innerHTML = `
<td><input type="text" class="labelInput" placeholder="标签"></td>
<td><input type="number" class="valueInput" placeholder="值"></td>`;
tableBody.appendChild(newRow);
}

// 删除最后一行
function removeLastRow() {
var tableBody = document.getElementById('dataRows');
if (tableBody.rows.length > 1) {
tableBody.deleteRow(-1);
}
}

// 文件加载事件处理器
function loadFile(event) {
var file = event.target.files[0];
if (!file) return;

if (/\.xls$|\.xlsx$/.test(file.name)) {
var reader = new FileReader();
reader.onload = function(e) {
/* 读取工作簿 */
var bstr = e.target.result;
var wb = XLSX.read(bstr, { type: 'binary' });

/* 获取第一个工作表 */
var wsname = wb.SheetNames[0];
var ws = wb.Sheets[wsname];

/* 转换为数组 */
var data = XLSX.utils.sheet_to_json(ws);

/* 清除当前表格并填充新数据 */
var tableBody = document.getElementById('dataRows');
while (tableBody.firstChild) {
tableBody.removeChild(tableBody.firstChild);
}
data.forEach(item => {
addRow();
document.querySelectorAll('#dataRows .labelInput')[
document.querySelectorAll('#dataRows .labelInput').length - 1
].value = item.label || '';
document.querySelectorAll('#dataRows .valueInput')[
document.querySelectorAll('#dataRows .valueInput').length - 1
].value = item.value || '';
});
};
reader.readAsBinaryString(file);
} else {
document.getElementById('fileErrors').innerText = '请选择正确的文件格式(.xls 或 .xlsx)';
}
}

// 解析文件
function parseFile() {
updateChart();
document.getElementById('fileErrors').innerText = '';
}

// 初始化图表
updateChart();

HTML结构(index.html):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>饼图生成器</title>
<!-- 引入 ECharts 和 xlsx.js -->
<script src="https://cdn.bootcdn.net/ajax/libs/echarts/5.4.0/echarts.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.17.0/xlsx.full.min.js"></script>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="container">
<h1>饼图生成器</h1>
<form id="dataForm">
<label for="title">标题:</label><input type="text" id="title" placeholder="请输入标题">
<label for="subtitle">副标题:</label><input type="text" id="subtitle" placeholder="请输入副标题">
<table>
<thead>
<tr>
<th>标签</th>
<th></th>
</tr>
</thead>
<tbody id="dataRows">
<tr>
<td><input type="text" class="labelInput" placeholder="标签"></td>
<td><input type="number" class="valueInput" placeholder="值"></td>
</tr>
</tbody>
</table>
<button type="button" onclick="addRow()">添加行</button>
<button type="button" onclick="removeLastRow()">删除最后一行</button>
<button type="button" onclick="updateChart()">更新图表</button>
<input type="file" id="fileUpload" accept=".xls,.xlsx" onchange="loadFile(event)">
<button type="button" onclick="parseFile()">从文件生成图表</button>
<div id="fileErrors" class="error"></div>
</form>
<div id="chart"></div>
</div>

<script src="script.js"></script>
</body>
</html>

功能实现

UI

CSS样式表(style.css):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/* styles.css */

body {
font-family: Arial, sans-serif;
background: #f5f5f5;
}


#chart {
width: 600px;
height: 400px;
margin: 20px auto;
}

.container {
max-width: 800px;
margin: 0 auto;
padding: 20px;
background: white;
border-radius: 10px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

input[type="text"], input[type="number"] {
width: 100%;
padding: 8px;
margin: 5px 0;
border: 1px solid #ccc;
border-radius: 4px;
}

button {
display: block;
width: 100%;
padding: 10px;
margin-top: 10px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}

button:hover {
background-color: #45a049;
}

.error {
color: red;
}


最终效果
六班四分五裂


要使用饼状图工具,请访问Youreln工具箱charts页面
https://youreln.github.io/youreln-toolbox/charts.html