数据导入主要涉及三个步骤 1.文件上传;2.Excel解析;3.数据插入。 第三步就比较简单了,我们这里重点来看看前两个步骤。

文件上传

文件上传采用了ElementUI中的Upload控件,如下:

  1. <el-upload
  2. :show-file-list="false"
  3. accept="application/vnd.ms-excel"
  4. action="/emp/basic/importEmp"
  5. :on-success="fileUploadSuccess"
  6. :on-error="fileUploadError" :disabled="fileUploadBtnText=='正在导入'"
  7. :before-upload="beforeFileUpload" style="display: inline">
  8. <el-button size="mini" type="success" :loading="fileUploadBtnText=='正在导入'"><i class="fa fa-lg fa-level-up" style="margin-right: 5px"></i>{{fileUploadBtnText}}
  9. </el-button>
  10. </el-upload>

正在上传时,文件上传控件不可用,上传成功或者失败之后才可用,上传过程中,上传按钮会有loading显示。

然后在SpringMVC中接收上传文件即可:

@RequestMapping(value = "/importEmp", method = RequestMethod.POST)
public RespBean importEmp(MultipartFile file) {
    //...
}

Excel解析

将上传到的MultipartFile转为输入流,然后交给POI去解析即可。可以分为如下四个步骤:

1.创建HSSFWorkbook对象

HSSFWorkbook workbook = new HSSFWorkbook(new POIFSFileSystem(file.getInputStream()));

2.获取一共有多少sheet,然后遍历

int numberOfSheets = workbook.getNumberOfSheets();
for (int i = 0; i < numberOfSheets; i++) {
    HSSFSheet sheet = workbook.getSheetAt(i);
    //...
}

3.获取sheet中一共有多少行,遍历行(注意第一行是标题)

int physicalNumberOfRows = sheet.getPhysicalNumberOfRows();
Employee employee;
for (int j = 0; j < physicalNumberOfRows; j++) {
    if (j == 0) {
        continue;//标题行
    }
    //...
}

4.获取每一行有多少单元格,遍历单元格

int physicalNumberOfCells = row.getPhysicalNumberOfCells();
employee = new Employee();
for (int k = 0; k < physicalNumberOfCells; k++) {
    HSSFCell cell = row.getCell(k);
    //...
}

单元格的遍历就比较简单了,将遍历到的数据放入Employee实例中,每遍历一行,就将一个employee实例放入集合中。