将这段代码的功能用前端展示,写出前端和对应的后端代码
时间: 2024-11-12 08:44:22 浏览: 38
好的,我将为你提供一个简单的示例,展示如何将这段 Java 后端代码与前端页面结合起来。我们将使用 Spring Boot 作为后端框架,Vue.js 作为前端框架。
### 后端代码(Spring Boot)
首先,创建一个 Spring Boot 应用程序,并将现有的 Java 代码封装在一个服务中。
#### 1. 创建 Spring Boot 项目
你可以使用 Spring Initializr 来创建一个新的 Spring Boot 项目,选择以下依赖项:
- Spring Web
- Spring Boot DevTools
#### 2. 添加依赖项
在 `pom.xml` 中添加必要的依赖项:
```xml
<dependencies>
<!-- Spring Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Apache POI for Excel handling -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.2.3</version>
</dependency>
<!-- Apache Commons Text for Levenshtein Distance -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-text</artifactId>
<version>1.9</version>
</dependency>
</dependencies>
```
#### 3. 创建控制器和服务
创建一个控制器来处理前端请求,并创建一个服务类来执行主要逻辑。
##### Controller
```java
package com.example.excelmerge.controller;
import com.example.excelmerge.service.ExcelMergeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
@RestController
public class ExcelMergeController {
@Autowired
private ExcelMergeService excelMergeService;
@PostMapping("/merge-excel")
public ResponseEntity<String> mergeExcel(@RequestParam("file1") MultipartFile file1, @RequestParam("file2") MultipartFile file2) {
try {
excelMergeService.mergeExcel(file1, file2);
return ResponseEntity.ok("Files merged successfully!");
} catch (Exception e) {
return ResponseEntity.badRequest().body("Error merging files: " + e.getMessage());
}
}
}
```
##### Service
```java
package com.example.excelmerge.service;
import org.apache.commons.text.similarity.LevenshteinDistance;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Pattern;
@Service
public class ExcelMergeService {
private static final int SIMILARITY_THRESHOLD = 3;
private static final Pattern NUMERIC_PATTERN = Pattern.compile("\\d+");
public void mergeExcel(MultipartFile file1, MultipartFile file2) throws IOException {
try (Workbook workbook1 = new XSSFWorkbook(new ByteArrayInputStream(file1.getBytes()));
Workbook workbook2 = new XSSFWorkbook(new ByteArrayInputStream(file2.getBytes()))) {
Sheet sheet1 = workbook1.getSheetAt(0);
Sheet sheet2 = workbook2.getSheetAt(0);
Set<String> projectSet1 = new HashSet<>();
for (Row row : sheet1) {
Cell cell = row.getCell(0);
if (cell != null) {
projectSet1.add(cell.getStringCellValue().trim());
}
}
LevenshteinDistance levenshtein = new LevenshteinDistance();
Set<String> uniqueMissingProjects = new HashSet<>();
for (Row row : sheet2) {
Cell cell = row.getCell(6);
if (cell != null) {
String projectNames = cell.getStringCellValue().trim();
String[] projectArray = projectNames.split(", ");
for (String projectName2 : projectArray) {
projectName2 = projectName2.trim();
if (isNumeric(projectName2)) {
continue;
}
boolean isFound = false;
for (String projectName1 : projectSet1) {
int distance = levenshtein.apply(projectName2, projectName1);
if (distance <= SIMILARITY_THRESHOLD) {
System.out.println("Found similar project: " + projectName2 + " -> " + projectName1);
isFound = true;
break;
}
}
if (!isFound) {
uniqueMissingProjects.add(projectName2);
}
}
}
}
int lastRowNum = sheet1.getLastRowNum();
for (String missingProject : uniqueMissingProjects) {
Row newRow = sheet1.createRow(++lastRowNum);
newRow.createCell(0).setCellValue(missingProject);
newRow.createCell(2).setCellValue((int) (Math.random() * 100) + 1);
}
try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
workbook1.write(bos);
byte[] bytes = bos.toByteArray();
// Save the modified file or send it back to the client
// For simplicity, we will just print the length of the output
System.out.println("Modified file size: " + bytes.length + " bytes");
}
}
}
private boolean isNumeric(String str) {
return NUMERIC_PATTERN.matcher(str).matches();
}
}
```
### 前端代码(Vue.js)
#### 1. 创建 Vue.js 项目
你可以使用 Vue CLI 来创建一个新的 Vue.js 项目:
```sh
npm install -g @vue/cli
vue create excel-merge-app
cd excel-merge-app
```
#### 2. 安装 Axios
安装 Axios 用于发送 HTTP 请求:
```sh
npm install axios
```
#### 3. 创建组件
在 `src/components` 目录下创建一个名为 `ExcelMerge.vue` 的组件:
```vue
<template>
<div>
<h1>Excel Merge Tool</h1>
<form @submit.prevent="mergeExcel">
<input type="file" ref="file1" accept=".xlsx" required />
<input type="file" ref="file2" accept=".xlsx" required />
<button type="submit">Merge Files</button>
</form>
<div v-if="message">{{ message }}</div>
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
message: ''
};
},
methods: {
async mergeExcel() {
const file1 = this.$refs.file1.files[0];
const file2 = this.$refs.file2.files[0];
const formData = new FormData();
formData.append('file1', file1);
formData.append('file2', file2);
try {
const response = await axios.post('http://localhost:8080/merge-excel', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
});
this.message = response.data;
} catch (error) {
this.message = error.response ? error.response.data : 'An error occurred';
}
}
}
};
</script>
<style scoped>
/* Add some basic styling */
form {
display: flex;
flex-direction: column;
gap: 10px;
}
button {
padding: 10px;
background-color: #4CAF50;
color: white;
border: none;
cursor: pointer;
}
button:hover {
background-color: #45a049;
}
</style>
```
#### 4. 更新 App.vue
在 `src/App.vue` 中引入并使用 `ExcelMerge` 组件:
```vue
<template>
<div id="app">
<ExcelMerge />
</div>
</template>
<script>
import ExcelMerge from './components/ExcelMerge.vue';
export default {
name: 'App',
components: {
ExcelMerge
}
};
</script>
<style>
/* Add global styles if needed */
</style>
```
### 运行项目
1. 启动 Spring Boot 应用程序:
```sh
./mvnw spring-boot:run
```
2. 启动 Vue.js 应用程序:
```sh
npm run serve
```
现在,你应该能够在浏览器中访问 `http://localhost:8080` 并看到一个文件上传表单,可以上传两个 Excel 文件进行合并。
阅读全文
相关推荐


















