-
Notifications
You must be signed in to change notification settings - Fork 10.3k
25.使用POI实现Excel导入
江南一点雨 edited this page Jan 17, 2018
·
1 revision
数据导入主要涉及三个步骤 1.文件上传;2.Excel解析;3.数据插入。 第三步就比较简单了,我们这里重点来看看前两个步骤。
文件上传采用了ElementUI中的Upload控件,如下:
<el-upload
:show-file-list="false"
accept="application/vnd.ms-excel"
action="/emp/basic/importEmp"
:on-success="fileUploadSuccess"
:on-error="fileUploadError" :disabled="fileUploadBtnText=='正在导入'"
:before-upload="beforeFileUpload" style="display: inline">
<el-button size="mini" type="success" :loading="fileUploadBtnText=='正在导入'"><i class="fa fa-lg fa-level-up" style="margin-right: 5px"></i>{{fileUploadBtnText}}
</el-button>
</el-upload>
正在上传时,文件上传控件不可用,上传成功或者失败之后才可用,上传过程中,上传按钮会有loading显示。
然后在SpringMVC中接收上传文件即可:
@RequestMapping(value = "/importEmp", method = RequestMethod.POST)
public RespBean importEmp(MultipartFile file) {
//...
}
将上传到的MultipartFile转为输入流,然后交给POI去解析即可。可以分为如下四个步骤:
HSSFWorkbook workbook = new HSSFWorkbook(new POIFSFileSystem(file.getInputStream()));
int numberOfSheets = workbook.getNumberOfSheets();
for (int i = 0; i < numberOfSheets; i++) {
HSSFSheet sheet = workbook.getSheetAt(i);
//...
}
int physicalNumberOfRows = sheet.getPhysicalNumberOfRows();
Employee employee;
for (int j = 0; j < physicalNumberOfRows; j++) {
if (j == 0) {
continue;//标题行
}
//...
}
int physicalNumberOfCells = row.getPhysicalNumberOfCells();
employee = new Employee();
for (int k = 0; k < physicalNumberOfCells; k++) {
HSSFCell cell = row.getCell(k);
//...
}
单元格的遍历就比较简单了,将遍历到的数据放入Employee实例中,每遍历一行,就将一个employee实例放入集合中。