Vue+Spring Boot 를 사용 하여 Excel 업로드 기능 구현

1.Vue-cli 를 사용 하여 전단 항목 만 들 기
vue-cli 도 구 를 사용 하면 전단 프로젝트 를 쉽게 구축 할 수 있 습 니 다.물론 WebStorm 을 사용 하여 구축 하면 더욱 간결 합 니 다(그림 참조).본 고 는 웹 스 톰 을 추천 합 니 다.후속 개발 에서 IDE 는 우리 의 개발 을 더욱 간결 하 게 할 수 있 기 때 문 입 니 다.부분 설정 그림:


2.Navbar 작성
웹 앱 으로서 Navbar 는 응용 프로그램의 네 비게 이 션 표시 줄 로 서 없어 서 는 안 된다.이 프로젝트 에서 필 자 는 boottstrap 을 도입 하여 Navbar 를 쉽게 구축 했다.vue 에서 우 리 는 components 폴 더 에 우리 의 구성 요 소 를 추가 해 야 합 니 다.이 프로젝트 에 있어 Navbar 는 우리 가 가입 할 첫 번 째 구성 요소 입 니 다.그 는 router 외 에 독립 하여 웹 페이지 위 에 고정 되 어 있 습 니 다.
2.1 우선,vue,vue-cli,boottstrap 을 npm 로 설치 합 니 다.

npm install vue
npm install -g vue-cli
npm install --save bootstrap jquery popper.js
2.2 다음 에 우 리 는 components 디 렉 터 리 다음 new vue 구성 요 소 를 도입 하고 main.js 에서 boottstrap 의존 도 를 도입 합 니 다.

import 'bootstrap/dist/css/bootstrap.min.css'
import 'bootstrap/dist/js/bootstrap.min'
2.3 다음 에 코드 를 쓰기 시작 할 수 있 습 니 다.본 고 는 table 과 관련 된 기능 에 만 관심 을 가지 기 때문에 네 비게 이 션 표시 줄 에 Script 를 제외 한 의외 의 요 소 는 모두 disable 되 었 습 니 다.코드 는 다음 과 같 습 니 다.

<template>
 <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
 <span class="navbar-brand mb-0 h1">Vue-SpringBoot</span>
 <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
 <span class="navbar-toggler-icon"></span>
 </button>
 <div class="collapse navbar-collapse" id="navbarNav">
 <ul class="navbar-nav">
 <li class="nav-item">
  <router-link class="nav-link" to="/home">Home</router-link>
 </li>
 <li class="nav-item active">
  <router-link to="/" class="nav-link">Script</router-link>
 </li>
 <li class="nav-item">
  <router-link to="/history" class="nav-link">History</router-link>
 </li>
 </ul>
 </div>
 </nav>
</template>
<script>
 export default {
 name: "MyNavbar"
 }
</script>
<style scoped>
</style>
2.3 App.vue 에 MyNavbar 도입
3.Script 테이블 작성
자동화 도구 로 서 없어 서 는 안 될 부분 은 Script 를 도입 하 는 것 입 니 다.저 희 는 사용자 가 H5 인터페이스 로 Script 를 자 유 롭 게 작성 할 수 있 기 를 바 랍 니 다.그래서 여기 서 vue 의 데이터 양 방향 바 인 딩 을 사용 하여 Table CRUD 를 진행 합 니 다.
3.1 vue 구성 요소 스 크 립 트 테이블 을 새로 만 듭 니 다.코드 는 다음 과 같 습 니 다.

<template>
 <div class="container-fluid" id="scriptTable">
 <h3>My Script</h3>
 <form style="margin-top: 1rem">
 <input type="file" @change="getFile($event)" class="" multiple/>
 <input type="button" value="upload" @click="submit($event)" class="btn btn-dark">
 </form>
 <table class="table table-hover text-center table-bordered"
  style="word-break: break-all; word-wrap: break-word;margin-top: 1rem;">
 <thead>
 <th>#</th>
 <th>Platform</th>
 <th>Action</th>
 <th>Path</th>
 <th>Value</th>
 <th>Wait</th>
 <th>Screenshot</th>
 <th>Change</th>
 </thead>
 <tbody>
 <tr v-cloak v-for="(item, index) in steps">
 <th>{{index+1}}</th>
 <td>{{item.platform}}</td>
 <td>{{item.action}}</td>
 <td>{{item.path}}</td>
 <td>{{item.value}}</td>
 <td>{{item.wait}}</td>
 <td>{{item.screenshot}}</td>
 <td><a href="#" v-on:click="edit(item)">Edit</a> | <a href="#" v-on:click='aaa(index)'>Delete</a>
 </td>
 </tr>
 <tr>
 <th></th>
 <td><select class="form-control" v-model="stepstemp.platform">
  <option>Web</option>
  <option>Android</option>
 </select></td>
 <td><select class="form-control" v-model="stepstemp.action">
  <option>click</option>
  <option>get</option>
  <option>input</option>
  <option>swipe</option>
 </select></td>
 <td><input class="form-control" v-model="stepstemp.path" placeholder="Enter the xPath"></td>
 <td><input class="form-control" v-model="stepstemp.value" placeholder="Enter the input value"></td>
 <td><input class="form-control" v-model="stepstemp.wait" placeholder="Waiting seconds"></td>
 <td><select class="form-control" v-model="stepstemp.screenshot">
  <option>yes</option>
  <option>no</option>
 </select></td>
 <td>
  <button class="btn btn-sm btn-dark" v-on:click='save' v-if="isNotEdit">Save</button>
  <button class="btn btn-sm btn-primary" v-on:click='saveEdit' v-else>SaveEdit</button>
 </td>
 </tr>
 </tbody>
 </table>
 <hr/>
 </div>
</template>
<script>
 import Vue from 'vue'
 import axios from 'axios'
 export default {
 name: "ScriptTable",
 data() {
 return ({
 steps: [],
 stepstemp: {
  platform: '',
  action: '',
  path: '',
  value: '',
  wait: '',
  screenshot: ''
 },
 isNotEdit: true
 });
 },
 methods: {
 save: function () {
 this.steps.push(this.stepstemp);
 this.stepstemp = {
  platform: '',
  action: '',
  path: '',
  value: '',
  wait: '',
  screenshot: ''
 };
 },
 aaa: function (index) {
 this.steps.splice(index, 1)
 },
 edit: function (item) {
 this.isNotEdit = false;
 this.stepstemp = item;
 },
 saveEdit: function () {
 this.isNotEdit = true;
 this.stepstemp = {
  platform: '',
  action: '',
  path: '',
  value: '',
  wait: '',
  screenshot: ''
 };
 }
 }
 }
</script>
<style scoped>
</style>
3.3 dev, localhost:8080 npm run dev전단 페이지 효 과 는 다음 과 같 습 니 다:

이로써 본 논문 과 관련 된 순 전단 부분 은 완성 지 차이 가 많 지 않 고 mock 의 데 이 터 를 더 한 후에 우 리 는 백 엔 드 개발 을 시작 할 수 있다.
4.Spring Initializr 를 사용 하여 백 엔 드 프로젝트 만 들 기
프로젝트 를 쉽게 구축 하고 RESTful API 를 구축 하 며 요청 처 리 를 쉽게 설정 하기 위해 필 자 는 Spring Boot 를 백 엔 드 프레임 워 크 로 선택 했다.
4.1 먼저 IDEA 가 통합 한 Spring Initializr 를 사용 하여 프로젝트 를 구축 합 니 다.일부 설정 은 그림 과 같 습 니 다.

4.2 다음 pom.xml 에 poi 의존 도 를 도입 하고 import change 를 클릭 합 니 다.다음 과 같다.

<dependency>
 <groupId>org.apache.poi</groupId>
 <artifactId>poi-ooxml</artifactId>
 <version>4.0.0</version>
 </dependency>
4.3 다음 에 저 희 는 application.properties 에서 server.port=8088 을 설정 하여 전단 항목 과 분리 합 니 다.
5.pojo 클래스 Step 의 작성
다음은 pojo 류 에 대한 작성 입 니 다.본 고 에 필요 한 pojo 는 Step 하나 뿐 입 니 다.전단 의 table 과 대응 합 니 다.코드 는 다음 과 같 습 니 다.

import lombok.Data;
@Data
public class Step {
 private String platform;
 private String action;
 private String path;
 private String value;
 private int wait;
 private String screenshot;
}
6.UploadController 의 작성
다음은 전단 Post 에서 요청 한 Handler(Controller)를 작성 합 니 다.이 Post 요청 을"/uploadfile"과 대응 하여 업로드 할 것 입 니 다.@CrossOrigin 주 해 를 추가 하여 크로스 필드 를 실현 하 는 것 에 주의 하 십시오.코드 는 다음 과 같 습 니 다.

package com.daniel.vuespringbootuploadbe;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
@Controller
@CrossOrigin
@ResponseBody
public class UploadController {
 private static String UPLOADED_FOLDER = "src/main/resources/static/temp/";
 @Autowired
 private LoadService loadService;
 @PostMapping("/upload")
 public List<Step> singleFileUpload(MultipartFile file) {
 try {
  // Get the file and save it somewhere
  byte[] bytes = file.getBytes();
  Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename());
  Files.write(path, bytes);
 } catch (IOException e) {
  e.printStackTrace();
 }
 // Print file data to html
 List<Step> result = loadService.castToStep(new File(UPLOADED_FOLDER + file.getOriginalFilename()));
 return result;
 }
}
7.LoadService 의 작성
요청 에 전 송 된 파일 을 읽 기 위해 Service 를 작성 해 야 합 니 다.쉽게 말 하면 Excel 의 Script 를 pojo 의 링크 로 변환 하고 Controller 에서 Response Body 로 되 돌려 줍 니 다.
7.1 먼저 Service 인 터 페 이 스 를 만 듭 니 다.코드 는 다음 과 같 습 니 다.

package com.daniel.vuespringbootuploadbe;
import org.springframework.stereotype.Service;
import java.io.File;
import java.util.List;
@Service
public interface LoadService {
 List<Step> castToStep(File file);
}
7.2 다음 에 Service 실현 클래스 를 만 듭 니 다.코드 는 다음 과 같 습 니 다.

package com.daniel.vuespringbootuploadbe;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
@Service
public class LoadServiceImpl implements LoadService {
 @Override
 public List<Step> castToStep(File file) {
 List<Step> steps = new ArrayList<>();
 Workbook workbook = null;
 try {
  workbook = new XSSFWorkbook(file);
 } catch (IOException e) {
  e.printStackTrace();
 } catch (InvalidFormatException e) {
  e.printStackTrace();
 }
 Sheet sheet = workbook.getSheetAt(0);
 int num = sheet.getLastRowNum() - sheet.getFirstRowNum();
 //Read steps
 for (int i = 0; i < num; i++) {
  Row row = sheet.getRow(i+1);
  Step step = new Step();
  step.setPlatform(row.getCell(0).getStringCellValue());
  step.setAction(row.getCell(1).getStringCellValue());
  step.setPath(row.getCell(2).getStringCellValue());
  step.setValue(row.getCell(3).getStringCellValue());
  step.setWait((int) row.getCell(4).getNumericCellValue());
  step.setScreenshot(row.getCell(5).getStringCellValue());
  steps.add(step);
 }
 try {
  workbook.close();
 } catch (IOException e) {
  e.printStackTrace();
 }
 return steps;
 }
}
8.간단 한 RESTful API 구축
글 이 막바지 에 이 르 렀 습 니 다.현재 전후 단의 독립 코드 가 기본적으로 개발 되 었 습 니 다.RESTful 을 구축 할 때 가 되 었 습 니 다.본 논문 의 API 는 매우 간단 합 니 다.바로 업로드 에 응답 하고 돌아 온 json 을 인터페이스의 Table 에 기록 하여 Script 가 져 오기 를 완성 하 는 것 입 니 다.npm 에 axios 를 설치 한 후 ScriptTable 구성 요소 에 다음 과 같은 코드 를 추가 하 는 것 입 니 다.

getFile: function (event) {
 this.file = event.target.files[0];
 console.log(this.file);
 },
 submit: function (event) {
 event.preventDefault();
 let formData = new FormData();
 formData.append("file", this.file);
 axios.post('http://localhost:8088/upload', formData)
  .then(function (response) {
  for (let i = 0; i < response.data.length; i++) {
  var tempData = {
  platform: response.data[i].platform,
  action: response.data[i].action,
  path: response.data[i].path,
  value: response.data[i].value,
  wait: response.data[i].wait,
  screenshot: response.data[i].screenshot
  };
  this.steps.push(tempData);
  }
  }.bind(this))
  .catch(function (error) {
  alert("Fail");
  console.log(error);
  });
 }
9.서비스 실행,스 크 립 트 작성 및 업로드
다음 에 우 리 는 Excel 을 만 들 고 그림 형식 에 따라 간단 한 Script 를 작성 하 며 앞 뒤 서 비 스 를 실행 하여 업 로드 를 실현 합 니 다.

실행 후 Excel 파일 은 백 엔 드 프로젝트 의 static temp 디 렉 터 리 에 업 로드 됩 니 다.
총결산
위 에서 말 한 것 은 편집장 님 께 서 소개 해 주신 Vue+Spring Boot 를 사용 하여 엑셀 업로드 기능 을 실현 하 는 것 입 니 다.여러분 께 도움 이 되 기 를 바 랍 니 다.궁금 한 점 이 있 으 시 면 댓 글로 남 겨 주세요.편집장 님 께 서 바로 답 해 드 리 겠 습 니 다.여기 서도 저희 사이트 에 대한 여러분 의 지지 에 감 사 드 립 니 다!

좋은 웹페이지 즐겨찾기