使用springboot和vue写一个excel上传至数据库的代码
时间: 2024-02-21 09:02:26 浏览: 125
好的,下面是使用Spring Boot和Vue.js实现Excel上传至数据库的代码:
1. 前端代码(Vue.js)
```
<template>
<div>
<input type="file" ref="fileInput" @change="uploadExcel">
</div>
</template>
<script>
export default {
methods: {
uploadExcel() {
let file = this.$refs.fileInput.files[0];
let formData = new FormData();
formData.append('file', file);
axios.post('/api/uploadExcel', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
}).then(response => {
console.log(response.data);
}).catch(error => {
console.log(error);
});
}
}
}
</script>
```
2. 后端代码(Spring Boot)
```
@RestController
@RequestMapping("/api")
public class ExcelController {
@Autowired
private ExcelService excelService;
@PostMapping("/uploadExcel")
public ResponseEntity<?> uploadExcel(@RequestParam("file") MultipartFile file) {
try {
excelService.saveExcel(file);
return ResponseEntity.ok().build();
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
}
}
@Service
public class ExcelService {
@Autowired
private ExcelRepository excelRepository;
public void saveExcel(MultipartFile file) throws Exception {
List<ExcelEntity> entities = ExcelUtils.readExcel(file.getInputStream(), ExcelEntity.class);
excelRepository.saveAll(entities);
}
}
@Entity
@Table(name = "excel")
public class ExcelEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "name")
private String name;
@Column(name = "age")
private Integer age;
// getters and setters
}
public interface ExcelRepository extends JpaRepository<ExcelEntity, Long> {
}
```
3. ExcelUtils.java(用于读取Excel文件并转换为实体类)
```
public class ExcelUtils {
public static <T> List<T> readExcel(InputStream inputStream, Class<T> clazz) throws Exception {
Workbook workbook = new XSSFWorkbook(inputStream);
Sheet sheet = workbook.getSheetAt(0);
List<T> list = new ArrayList<>();
for (int i = 1; i <= sheet.getLastRowNum(); i++) {
Row row = sheet.getRow(i);
T entity = clazz.newInstance();
for (int j = 0; j < row.getLastCellNum(); j++) {
Cell cell = row.getCell(j);
Field field = clazz.getDeclaredField(getFieldName(j));
field.setAccessible(true);
if (String.class == field.getType()) {
field.set(entity, cell.getStringCellValue());
} else if (Integer.class == field.getType()) {
field.set(entity, (int) cell.getNumericCellValue());
}
}
list.add(entity);
}
return list;
}
private static String getFieldName(int index) {
switch (index) {
case 0:
return "name";
case 1:
return "age";
default:
return null;
}
}
}
```
这样就完成了Excel上传至数据库的功能。需要注意的是,以上代码只适用于上传第一个Sheet的数据,如果有多个Sheet,需要根据实际情况进行修改。
阅读全文