了解了你的需求是通过 Java 前端上传一个 Excel 文件后,下面是一个简单的示例,演示如何结合 Spring Boot 框架来实现文件上传和读取 Excel 文件的内容。
1. 引入所需依赖
确保你的 pom.xml 包含以下依赖:
xml Copy code
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
</dependency>
2. 创建文件上传控制器
这里是一个简单的 Spring Boot 控制器,用于处理文件上传:
java Copy code
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.Iterator;
@RestController
@RequestMapping("/upload")
public class FileUploadController {
@PostMapping("/excel")
public String uploadExcelFile(@RequestParam("file") MultipartFile file) {
if (file.isEmpty()) {
return "File is empty!";
}
try (Workbook workbook = new XSSFWorkbook(file.getInputStream())) {
// 获取第一个工作表
Sheet sheet = workbook.getSheetAt(0);
Iterator<Row> rows = sheet.iterator();
StringBuilder data = new StringBuilder();
while (rows.hasNext()) {
Row currentRow = rows.next();
Iterator<Cell> cellsInRow = currentRow.iterator();
while (cellsInRow.hasNext()) {
Cell currentCell = cellsInRow.next();
switch (currentCell.getCellType()) {
case STRING:
data.append(currentCell.getStringCellValue()).append(" ");
break;
case NUMERIC:
data.append(currentCell.getNumericCellValue()).append(" ");
break;
default:
data.append(" ");
}
}
data.append("\n");
}
return data.toString();
} catch (IOException e) {
e.printStackTrace();
return "Error reading Excel file: " + e.getMessage();
}
}
}
3. 配置前端 HTML 登录页面
创建一个简单的 HTML 界面,在前端进行文件上传:
html Copy code
<!DOCTYPE html>
<html>
<head>
<title>Upload Excel File</title>
</head>
<body>
<h1>Upload Excel File</h1>
<form method="post" action="/upload/excel" enctype="multipart/form-data">
<input type="file" name="file" />
<button type="submit">Upload</button>
</form>
</body>
</html>
以上 HTML 文件可以作为你的前端页面,用于上传 Excel 文件。
4. 运行应用
启动你的 Spring Boot 应用服务器,然后打开浏览器,访问相应的 URL,加载你的上传页面,选择一个 Excel 文件并点击上传。
java Copy code
@SpringBootApplication
public class ExcelUploadApplication {
public static void main(String[] args) {
SpringApplication.run(ExcelUploadApplication.class, args);
}
}
详细解释
导入依赖 :
org.springframework.boot:spring-boot-starter-web:用来创建 Web 应用。
org.apache.poi:poi 和 org.apache.poi:poi-ooxml:用于处理 Excel 文件。
创建上传控制器 :
使用 @RestController 和 @RequestMapping 注解定义控制器。
uploadExcelFile 方法用于处理上传的 Excel 文件,首先检查文件是否为空,然后使用 Apache POI 解析文件内容,并将读取的数据返回。
前端 HTML 表单 :
创建一个简单的表单,用于选择并上传 Excel 文件到 /upload/excel 处理路径。
运行并测试应用 :
启动 Spring Boot 应用,访问 HTML 表单页面,选择并上传 Excel 文件进行测试。
通过以上步骤,你应该能够实现一个简单的 Excel 文件上传和解析的功能。希望这个示例对你有所帮助!