前端上传Excel文件并使用Thymeleaf和Spring Boot解析数据
首先,前端需要使用HTML和Bootstrap创建一个文本框和两个按钮:
<div class='form-group'>
<label for='excelFile'>Excel文件</label>
<input type='file' class='form-control-file' id='excelFile' accept='.xlsx,.xls'>
</div>
<button type='button' class='btn btn-primary' id='uploadBtn'>上传</button>
<button type='button' class='btn btn-secondary' id='cancelBtn'>取消</button>
这里使用了Bootstrap的样式来美化表单。
接下来,我们需要使用JavaScript来处理按钮的点击事件,将Excel文件发送到后端进行处理:
document.getElementById('uploadBtn').addEventListener('click', function() {
// 获取文件
var file = document.getElementById('excelFile').files[0];
if (!file) {
alert('请选择一个Excel文件!');
return;
}
// 创建FormData对象,用于发送文件
var formData = new FormData();
formData.append('file', file);
// 发送请求
var xhr = new XMLHttpRequest();
xhr.open('POST', '/uploadExcel');
xhr.onload = function() {
if (xhr.status === 200) {
// 处理响应数据
var data = JSON.parse(xhr.responseText);
console.log(data);
} else {
alert('上传失败!');
}
};
xhr.send(formData);
});
document.getElementById('cancelBtn').addEventListener('click', function() {
// 清空文件选择框
document.getElementById('excelFile').value = '';
});
这里使用了XMLHttpRequest对象来发送POST请求,并使用JSON格式处理响应数据。
在后端,我们需要使用Spring Boot来处理上传请求,解析Excel文件并将数据存储到数组中:
@PostMapping('/uploadExcel')
@ResponseBody
public List<List<String>> uploadExcel(@RequestParam('file') MultipartFile file) throws IOException {
// 解析Excel文件
Workbook workbook;
if (file.getOriginalFilename().endsWith('.xlsx')) {
workbook = new XSSFWorkbook(file.getInputStream());
} else {
workbook = new HSSFWorkbook(file.getInputStream());
}
Sheet sheet = workbook.getSheetAt(0);
// 存储数据到数组中
List<List<String>> data = new ArrayList<>();
for (Row row : sheet) {
List<String> rowData = new ArrayList<>();
for (Cell cell : row) {
rowData.add(cell.getStringCellValue());
}
data.add(rowData);
}
return data;
}
这里使用了@RequestParam注解来获取上传的文件,使用Workbook对象解析Excel文件,并将数据存储到一个二维数组中。最后,使用@ResponseBody注解将数据以JSON格式返回给前端。
原文地址: https://www.cveoy.top/t/topic/oeL6 著作权归作者所有。请勿转载和采集!