需求:将上传的excel文件进行接收及解析,并且将每行的内容都输出为字符串。
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
@RestController
public class FileUploadController {
@PostMapping("/upload")
public String handleFileUpload(@RequestPart("file") MultipartFile file) {
try {
InputStream inputStream = file.getInputStream();
Workbook workbook = new XSSFWorkbook(inputStream);
Sheet sheet = workbook.getSheetAt(0);
StringBuilder content = new StringBuilder();
int rowCount = 0;
for (Row row : sheet) {
// 跳过标题栏
if(rowCount == 0){
rowCount++;
continue;
}
for (Cell cell : row) {
content.append(cell).append("\t");
}
content.append("\n");
}
workbook.close();
return content.toString();
} catch (IOException e) {
e.printStackTrace();
return "Error occurred while processing the file";
}
}
}