一、代码1
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>读取 CSV 文件示例</title>
</head>
<body>
<input type="file" id="input">
<table id="output"></table>
<script>
// 获取 input 标签和 output 标签
const input = document.getElementById('input');
const output = document.getElementById('output');
// 当用户选择文件时执行
input.addEventListener('change', function() {
// 读取文件
const reader = new FileReader();
reader.readAsText(input.files[0]);
// 当文件读取完成时执行
reader.onload = function() {
// 解析 CSV 文件
const csv = reader.result;
const lines = csv.split('\n');
const headers = lines[0].split(',');
const data = lines.slice(1).map(line => line.split(','));
// 渲染表格
output.innerHTML = `
<thead>
<tr>
${headers.map(header => `<th>${header}</th>`).join('')}
</tr>
</thead>
<tbody>
${data.map(row => `
<tr>
${row.map(cell => `<td>${cell}</td>`).join('')}
</tr>
`).join('')}
</tbody>
`;
};
});
</script>
</body>
</html>
二、效果1
三、代码2
添加一些样式。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>读取 CSV 文件示例</title>
<style>
/* 设置表格样式 */
table {
margin: 20px auto;
border-collapse: collapse;
width: 80%;
background-color: #fff;
box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
}
caption {
font-size: 24px;
font-weight: bold;
text-align: center;
padding-bottom: 10px;
}
/* 设置奇偶行的背景色 */
tr:nth-child(odd) {
background-color: #f2f2f2;
}
/* 设置表格列的边框样式和文本居中 */
th, td {
border: 1px solid #ccc;
text-align: center;
padding: 8px;
}
</style>
</head>
<body>
<input type="file" id="input">
<table id="output">
<caption>CSV 文件内容</caption>
</table>
<script>
// 获取 input 标签和 output 标签
const input = document.getElementById('input');
const output = document.getElementById('output');
// 当用户选择文件时执行
input.addEventListener('change', function() {
const file = input.files[0];
// 判断文件是否为 CSV 格式
if (file && file.type === 'text/csv') {
// 读取文件
const reader = new FileReader();
reader.readAsText(file);
// 当文件读取完成时执行
reader.onload = function() {
// 解析 CSV 文件
const csv = reader.result;
const lines = csv.split('\n');
const headers = lines[0].split(',');
const data = lines.slice(1).map(line => line.split(','));
// 渲染表格
output.innerHTML = `
<caption>CSV 文件内容</caption>
<thead>
<tr>
${headers.map(header => `<th>${header}</th>`).join('')}
</tr>
</thead>
<tbody>
${data.map(row => `
<tr>
${row.map(cell => `<td>${cell}</td>`).join('')}
</tr>
`).join('')}
</tbody>
`;
};
} else {
// 不是 CSV 格式文件,清空表格并更新标题
output.innerHTML = '';
output.caption.innerText = '请选择 CSV 格式文件!';
}
});
</script>
</body>
</html>
四、效果2