前端上传excel转换成json并传给后台
时间: 2023-08-01 21:06:06 浏览: 254
前端上传excel并转换成JSON的流程如下:
1. 用户在前端页面选择上传Excel文件;
2. 前端使用相关库(例如xlsx、FileReader等)将Excel文件解析成JSON格式;
3. 将解析后的JSON数据通过Ajax请求发送给后台服务。
下面是一个实现上传Excel并转换成JSON的示例代码:
HTML部分:
```
<input type="file" id="excel-file">
<button onclick="upload()">上传</button>
```
JavaScript部分:
```
function upload() {
let fileInput = document.getElementById('excel-file');
let file = fileInput.files[0];
let reader = new FileReader();
reader.readAsArrayBuffer(file);
reader.onload = function(e) {
let data = new Uint8Array(reader.result);
let workbook = XLSX.read(data, {type: 'array'});
let jsonData = XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]]);
sendData(jsonData);
}
}
function sendData(data) {
$.ajax({
url: '/upload',
type: 'POST',
data: JSON.stringify(data),
contentType: 'application/json',
success: function(response) {
console.log(response);
},
error: function(error) {
console.log(error);
}
});
}
```
这里使用了xlsx库来解析Excel文件,并将解析后的JSON数据通过Ajax请求发送给后台服务(假设后台服务的URL为/upload)。前端发送的数据需要设置Content-Type为application/json,以便后台能够正确解析JSON数据。
阅读全文
相关推荐

















