vue+springboot上传excel文件并读取

样例
样例
前端代码:

<div>
        <el-upload drag
                   :limit=limitNum
                   :auto-upload="false"
                   accept=".xlsx"
                   action=""
                   :before-upload="beforeUploadFile"
                   :on-change="fileChange"
                   :on-exceed="exceedFile"
                   :file-list="fileList">
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
          <div class="el-upload__tip" slot="tip">只能上传xlsx文件</div>
        </el-upload>
        <br/>
        <el-button size="small" type="primary" @click="uploadFile">立即导入</el-button>
        <el-button size="small" type="primary" >下载模板</el-button>
        <el-button size="small" @click="cancelUpdate">取消</el-button>
      </div>
<script>
export default {
  name: "FacultyInformation",
  data() {
    thisVue = this;
    return {
      limitNum:1,
      fileList: [],
      }
     }
methods: {
    handleClose(done) {
      this.fileList=[]
      done();
    },
    // 文件超出个数限制时的钩子
    exceedFile(files, fileList) {
      this.$message.warning(`只能选择 ${this.limitNum} 个文件,当前共选择了 ${files.length + fileList.length}`);
    },
    // 文件状态改变时的钩子
    fileChange(file, fileList) {
      console.log('file:',file.raw)
      console.log('fileList:',this.fileList)
      this.fileList.pop();
      this.fileList.push(file.raw);
    },
    // 上传文件之前的钩子, 参数为上传的文件,若返回 false 或者返回 Promise 且被 reject,则停止上传
    beforeUploadFile(file) {
      let extension = file.name.substring(file.name.lastIndexOf('.') + 1);
      if (extension !== 'xlsx') {
        this.$message.warning('只能上传后缀是.xlsx的文件');
      }
    },
    //取消上传
    cancelUpdate(){
      this.dialogVisible=!this.dialogVisible
      this.fileList=[]
    },
    uploadFile() {
      if (this.fileList.length === 0) {
        this.$message.warning('请上传文件');
      } else {
      //通过formData的文件传输,必须配置头部,否则将不能正常传输
        const config = {
          headers: { "Content-Type": "multipart/form-data;boundary="+new Date().getTime() },
          isNative:true,
        };
        let form = new FormData();
        var res;
        form.append('file', this.fileList[0]);
        // 请求自己服务器上传文件的接口
        axios.post("/uploadFacultyExcel",form,config).then(function (response) {
          console.log('response:',response);
          alert(response)
          //导入成功,文件栏清空
          var res=response.toString().substr(0,5)
          if (res==="导入成功,"){
            //导入成功刷新页面
            window.location.reload()
          }
        })
      }
    },
    inputFile(){

    }
  },
  }
</script>

后端代码
controller

@RestController
public class ExcelImportController {
    @Autowired
    ExcelImportService excelImportService;

    //上传表格到服务器
    @RequestMapping("/uploadStudentExcel")
    @ResponseBody
    public String uploadStudentExcel(@RequestParam("file") MultipartFile file){
        return excelImportService.uploadStudentExcel(file);
    }
}

service

public interface ExcelImportService {
    String uploadFacultyExcel(MultipartFile file);
    String uploadStudentExcel(MultipartFile file);
}

serviceImpl

@Service
@Transactional
@Slf4j
public class ExcelImportServiceImpl implements ExcelImportService {
    static String fileName;

 

    @Override
    public String uploadStudentExcel(MultipartFile file) {
        XSSFSheet sheetAt = uploadExcel(file);
        //获取最后一行的num,即总行数
        int maxRow = sheetAt.getLastRowNum();
        System.out.println("总行数:" + maxRow);

        for (int row = 1; row <= maxRow; row++) {
            //获取最后一个单元格的num,即每行总的单元格数,此处从1开始计数
            int maxRol = sheetAt.getRow(0).getLastCellNum();

            for (int rol = 0; rol < maxRol; rol++) {
                if (sheetAt.getRow(row).getCell(rol) == null) {
                    return "表格中第"+(row+1)+"行第"+ (char)(65+rol)+"列存在空数据!请修改后重新导入!";
                }
            }
            int finalRow = row;
            XSSFRow sheetAtRow = sheetAt.getRow(row);
            //查询班级是否存在
            XSSFCell period1 = sheetAtRow.getCell(1);
            period1.setCellType(CellType.STRING);
            String period =period1.getStringCellValue();

            XSSFCell classNumber1 = sheetAtRow.getCell(2);
            classNumber1.setCellType(CellType.STRING);
            String classNumber =classNumber1.getStringCellValue();
            MStudentClass mStudentClass = (MStudentClass) HSUtil.query("select e from MStudentClass as e where e.classNumber=:classNumber and e.period=:period and e.deleted=:deleted")
                    .setParameter("classNumber", classNumber)
                    .setParameter("period", period)
                    .setParameter("deleted", false)
                    .uniqueResult();
            if (mStudentClass == null) {
                return "导入的数据中"+period+"届"+classNumber+"班不存在,请先创建班级!";
            }
            //存入数据库
            MStudent mStudent = MStudent.create(e -> {
                XSSFCell studentIDCard = sheetAtRow.getCell(0);
                studentIDCard.setCellType(CellType.STRING);
                e.setStudentIDCard(studentIDCard.getStringCellValue());
                e.setMStudentClass(mStudentClass);

                e.setName(String.valueOf(sheetAtRow.getCell(3)));
                if (String.valueOf(sheetAtRow.getCell(4)).equals("男")) {
                    e.setPersonGender(EMPersonGender.BOY);
                } else if (String.valueOf(sheetAtRow.getCell(4)).equals("女")) {
                    e.setPersonGender(EMPersonGender.GIRL);
                } else {
                    e.setPersonGender(EMPersonGender.UNKNOWN);
                }
                e.setCertificateNo(String.valueOf(sheetAtRow.getCell(5)));
                e.setGatherType(EMGatherType.UNCHECKED);
                e.setSyncState(EMSyncState.TOBESYNCHRONIZED);
            });
        }
        //使用完后删除文件
        File deleteFile = new File(fileName);
        deleteFile.delete();
        return "导入成功!";
    }

    //将excel表上传到服务器
    public XSSFSheet uploadExcel(MultipartFile file) {
        String realPath = "D:\\Download\\uploads\\upload";
        File folder = new File(realPath);
        if (!folder.exists()) {
            folder.mkdir();
        }
        String newName = UUID.randomUUID().toString() + ".xlsx";
        try {
            file.transferTo(new File(folder, newName));

            fileName = realPath + "\\" + newName;
            FileInputStream newFile = new FileInputStream(fileName);
            //创建工作簿
            XSSFWorkbook xssfWorkbook = new XSSFWorkbook(newFile);
            //创建工作表
            XSSFSheet sheetAt = xssfWorkbook.getSheetAt(0);

            return sheetAt;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}

主要是前端通过formData以键值对的形式存储表格,然后通过axios访问接口,将文件上传到服务器的制定文件夹,然后后端去这个指定的文件夹拿取表格,进行读取,

  • 1
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
实现Excel文件上传到数据库有多种方法,以下是一种基于Spring Boot和Vue实现方式: 1. 前端页面实现Vue的前端页面中,添加一个文件上传组件,例如使用element-ui的el-upload组件: ```html <template> <el-upload class="upload-demo" action="/upload" // 文件上传的后端接口 :on-success="handleSuccess" :before-upload="beforeUpload"> <el-button size="small" type="primary">点击上传</el-button> </el-upload> </template> ``` 2. 后端接口实现 在Spring Boot后端实现一个文件上传的接口,例如使用Spring Boot自带的MultipartFile实现: ```java @RestController public class FileUploadController { @PostMapping("/upload") public String handleFileUpload(@RequestParam("file") MultipartFile file) { // 读取Excel文件,解析数据并插入到数据库中 ... return "success"; } } ``` 3. 解析Excel并插入到数据库中 在handleFileUpload方法中,可以使用Apache POI库来解析上传Excel文件,并将数据插入到数据库中。示例代码如下: ```java Workbook workbook = WorkbookFactory.create(file.getInputStream()); Sheet sheet = workbook.getSheetAt(0); for (Row row : sheet) { String name = row.getCell(0).getStringCellValue(); String age = row.getCell(1).getStringCellValue(); // 将数据插入到数据库中 ... } ``` 这样就可以实现Excel文件上传到数据库中了。需要注意的是,上传Excel文件需要符合一定的格式,例如第一列是姓名,第二列是年龄等等。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值