用HTML5读取Excel里面的数据,并展示出来
时间: 2024-03-23 13:40:30 浏览: 26
可以使用HTML5中的File API和JavaScript来读取Excel文件并展示数据。以下是一个简单的例子:
1. HTML代码:
```html
<input type="file" id="excelFile" onchange="handleFile(this)">
<table id="excelTable"></table>
```
2. JavaScript代码:
```javascript
function handleFile(e) {
// 获取上传的文件
var file = e.files[0];
// 创建一个FileReader对象
var reader = new FileReader();
// 读取Excel文件
reader.onload = function(e) {
var data = e.target.result;
var workbook = XLSX.read(data, {type: 'binary'});
var sheet = workbook.Sheets[workbook.SheetNames[0]];
// 转换为JSON格式
var json = XLSX.utils.sheet_to_json(sheet);
// 渲染表格
renderTable(json);
};
reader.readAsBinaryString(file);
}
function renderTable(data) {
var table = document.getElementById("excelTable");
// 清空表格
table.innerHTML = "";
// 表头
var header = Object.keys(data[0]);
var tr = document.createElement("tr");
header.forEach(function(key) {
var th = document.createElement("th");
th.textContent = key;
tr.appendChild(th);
});
table.appendChild(tr);
// 表格数据
data.forEach(function(row) {
var tr = document.createElement("tr");
header.forEach(function(key) {
var td = document.createElement("td");
td.textContent = row[key];
tr.appendChild(td);
});
table.appendChild(tr);
});
}
```
这个例子使用了SheetJS库来处理Excel文件。需要先在HTML中引入SheetJS:
```html
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.16.8/xlsx.full.min.js"></script>
```
注意,这个例子只支持读取XLSX格式的Excel文件,如果要支持其他格式,需要修改代码。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)