我有一个要求,需要通过邮递员请求上传一个excel文件并使用spring-boot WebFlux读取该excel文件的所有行。
我想知道有没有办法做到这一点?
我使用的是spring-boot版本2.3.9和Java1.8。
谢谢。
首先,您必须创建一个端点,通过POST请求接受.xlsx
文件,然后使用Apache POI读取Excel文件的每一行。
步骤1:
创建接受MultiartFiles
的端点。本教程解释了所有内容,甚至使用了Postman
。
步骤2:
在你的后端得到文件后,你会想要处理它。Apache POI会在这里提供帮助。首先,通过将其添加到pom
:中,将其包含到您的项目中
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>5.0.0</version>
</dependency>
这里有一个关于如何使用ApachePoi:读取文件的简单片段
try
{
FileInputStream file = // the file that you get from the request, transformed into a FileInputStream
//Creation of the Workbook that holds as reference the Excel file
XSSFWorkbook workbook = new XSSFWorkbook(file);
//Getting the first sheet of the workbook
XSSFSheet sheet = workbook.getSheetAt(0);
//Iterate through each rows one by one
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext())
{
Row row = rowIterator.next();
//For each row, iterate through all the columns
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext())
{
Cell cell = cellIterator.next();
//Check the cell type and format accordingly, other cell types exist, you may want to check them out
switch (cell.getCellType())
{
case Cell.CELL_TYPE_NUMERIC:
System.out.print(cell.getNumericCellValue());
break;
case Cell.CELL_TYPE_STRING:
System.out.print(cell.getStringCellValue());
break;
}
}
}
file.close();
}
catch (Exception e)
{
e.printStackTrace();
}