Springboot从excel中拿数据代码
时间: 2024-02-02 13:02:40 浏览: 33
可以参考以下代码:
1. 使用POI库读取Excel文件
2. 创建实体类来存储读取到的数据
3. 使用@Service注解将读取Excel数据的代码封装为服务
4. 在Controller中调用服务获取Excel数据并返回给前端
示例代码:
1. 读取Excel文件
```
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Component;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
@Component
public class ExcelReaderService {
public List<ExcelData> readExcelData(String filePath) throws IOException {
List<ExcelData> dataList = new ArrayList<>();
FileInputStream excelFile = new FileInputStream(new File(filePath));
Workbook workbook = new XSSFWorkbook(excelFile);
Sheet datatypeSheet = workbook.getSheetAt(0);
Iterator<Row> iterator = datatypeSheet.iterator();
while (iterator.hasNext()) {
Row currentRow = iterator.next();
Iterator<Cell> cellIterator = currentRow.iterator();
ExcelData data = new ExcelData();
while (cellIterator.hasNext()) {
Cell currentCell = cellIterator.next();
if (currentCell.getCellType() == CellType.STRING) {
if (currentCell.getColumnIndex() == 0) {
data.setName(currentCell.getStringCellValue());
} else if (currentCell.getColumnIndex() == 1) {
data.setAge(currentCell.getStringCellValue());
}
}
}
dataList.add(data);
}
return dataList;
}
}
```
2. 实体类
```
public class ExcelData {
private String name;
private String age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
```
3. 服务类
```
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.List;
@Service
public class ExcelService {
public List<ExcelData> getExcelData(String filePath) throws IOException {
ExcelReaderService reader = new ExcelReaderService();
List<ExcelData> dataList = reader.readExcelData(filePath);
return dataList;
}
}
```
4. Controller
```
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.util.List;
@RestController
@RequestMapping("/excel")
public class ExcelController {
@Autowired
ExcelService service;
@GetMapping("/data")
public ResponseEntity<List<ExcelData>> getExcelData(@RequestParam(name = "filePath") String filePath) throws IOException {
List<ExcelData> dataList = service.getExcelData(filePath);
return ResponseEntity.ok(dataList);
}
}
```
以上代码实现了从Excel中读取数据并返回给前端的功能。请注意:代码中使用了Apache POI库来读取Excel文件。