SpringBoot:解析excel
解析Excel文件,可以使用Apache POI库
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
上代码:
/**
* <b>Function: </b> todo
*
* @program: 解析excel文件
* @Package: com.kingbal.king.dmp
* @author: dingcho
* @date: 2024/09/18
* @version: 1.0
* @Copyright: 2024 www.kingbal.com Inc. All rights reserved.
*/
@Slf4j
@Service
public class ExcelServiceImpl implements IExcelService {
@Override
public List<List<String>> readExcel(MultipartFile file) throws IOException {
List<List<String>> data = Lists.newArrayList();
Workbook workbook = new XSSFWorkbook(file.getInputStream());
Sheet sheet = workbook.getSheetAt(0);
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
List<String> rowData = new ArrayList<>();
Iterator<Cell> cellIterator = row.iterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
rowData.add(getCellValueAsString(cell));
}
data.add(rowData);
}
workbook.close();
return data;
}
private String getCellValueAsString(Cell cell) {
switch (cell.getCellTypeEnum()) {
case STRING:
return cell.getStringCellValue();
case NUMERIC:
return String.valueOf(cell.getNumericCellValue());
case BOOLEAN:
return String.valueOf(cell.getBooleanCellValue());
default:
return "";
}
}
}
readExcel
方法接受一个MultipartFile
类型的参数,这是Spring MVC中处理文件上传的类型。然后使用Apache POI的Workbook
和Sheet
类来读取Excel文件,并迭代每一行和每一个单元格,将单元格的值转换为字符串并存储到结果列表中。
要注意的是,这个例子假设Excel文件是XLSX格式,如果需要处理旧的XLS格式
请使用
HSSFWorkbook
代替XSSFWorkbook
原文地址:https://blog.csdn.net/yao_guai/article/details/142336954
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!