Home>Article>Java> How to import excel files in java

How to import excel files in java

王林
王林 Original
2019-12-09 15:50:47 4764browse

How to import excel files in java

Idea analysis:

1. We need to import, which actually means uploading the file first, and then reading the data of the file.

2. We need an imported template, because the Excel column we import needs to match our data fields, so we need to give it a specification, which is a template.

3. First, make a temporary table of imported information to store the information in the imported file. Whenever we import, we first clear the table information, then get the data and put it in, then we check the imported data, and finally import it all.

The purpose of this is to prevent the imported data and columns from being directly imported into the library without matching them.

Free video tutorial sharing:java online video

Code analysis

1. Front-end js code:

var actionPath = contextPath + "/alumni-import"; $(function() { //加载数据 loadData(); //上传文件 uploadFile({ subfix: ['xls'], subfixTip: "请选择Excel的xls文件!", successCall: function(data, status, a) { $('[name=attachementPath]').val(data.fileName); $.post(actionPath + "!importExcel", { "f_id": data.f_id }, function(data) { if (data.success) { alertify.alert(data.message); $("#myModal-import").modal("hide"); loadData(); } else { alertify.alert(data.message); } }, "json"); } }); //导入 $("#btn-import").click(function() { var html = template("importTpl"); $("#import-body").html(html); $("#myModal-import").modal(); }); //确认导入 $("#btn-sure").click(function() { var type = $("#indentity-type").val(); alertify.confirm("确定要全部导入吗?", function(e) { if (!e) { return; } else { $.post("/alumni-import!saveReal?type=" + type, function(data) { alertify.alert("导入成功!", function() { location.href = "/alumni!hrefPage"; }); }, "json"); } }); }); });50 function loadData() { var options = { url: actionPath + "!page" }; loadPaginationData(options); }

2. Backend Function code

The front end has four requests, one to initialize page data loading, of course, there is no data at the beginning; one to import file upload; one to confirm the import; one to jump back to the information page after the import is completed ( The information page has a batch import page that jumps to this import page).

I won’t talk about the last one after the first one. Let’s talk about the second and third.

(1) The second one

//上传文件后调用 public void importExcel() { try { //清空临时表的数据 baseAlumniImportSrv.deleteAll(); //读取文件 File file = gridFsDao.readFile(f_id); //把文件信息给临时表 int count = excelXYSrv.importExcel(file); //清空上传的文件 file.delete(); sendSuccessMsg(count, "上传成功" + count + "条数据"); } catch (IOException e) { LOGGER.error(e); sendFailMsg(null, "上传失败"); } }
@Override //使用MongoDB GridFS public File readFile(String f_id) { //拿到文件 GridFSDBFile gridFSFile = mongoGridFs.findOne(new Query(Criteria.where(F_ID).is(f_id))); if (gridFSFile == null) { return null; } String fileName = gridFSFile.getFilename(); String extension = fileName.substring(fileName.lastIndexOf("."), fileName.length()); InputStream ins = gridFSFile.getInputStream(); String tmpFile = UUID.randomUUID().toString() + extension; File file = new File(tmpFile); try { OutputStream os = new FileOutputStream(file); int bytesRead = 0; byte[] buffer = new byte[8192]; while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) { os.write(buffer, 0, bytesRead); } os.close(); ins.close(); } catch (IOException e) { e.printStackTrace(); } return file; }
/** * @param excelFile * 从excel中读取数据,并存储到数据库临时表中 * @return * @throws IOException */ @Override public int importExcel(File excelFile) throws IOException { List> datas = ExcelImportUtil.readExcel(excelFile); int count = 0; for (int i = 1; i < datas.size(); i++) { BaseAlumniImport entity = this.convert2Entity(datas.get(i)); this.baseAlumniImportSrv.save(entity); count++; } return count; }

(3) The third one

public void saveReal() { int count = 0; List importList = this.baseAlumniImportSrv.findAll(); for (int i = 0; i < importList.size(); i += 10) { List newlist = new ArrayList<>(); if ((i + 10) < importList.size()) { newlist = importList.subList(i, i + 10); } else { newlist = importList.subList(i, importList.size()); } count += excelXYSrv.saveReal(newlist, this.type); } sendSuccessMsg(count, "导入成功" + importList.size() + "条数据"); }
@Override public int saveReal(List importList, String type) { int count = 0; String alumniIdentityName = dicSrv.findById(DicAlumniIdentity.class, Integer.parseInt(type)).getValue(); for (BaseAlumniImport inst : importList) { LOGGER.info(inst.getId()); BaseAlumni v = this.importExportSrv.convert(inst); v.setId(IdKit.uuid()); v.setCreateTime(new Date()); v.setLastUpdate(new Date()); this.baseAlumnidDao.save(v); this.baseAlumniImportSrv.deleteById(inst.getId()); count++; } return count; }
@Override public int saveReal(List importList, String type) { int count = 0; String alumniIdentityName = dicSrv.findById(DicAlumniIdentity.class, Integer.parseInt(type)).getValue(); for (BaseAlumniImport inst : importList) { LOGGER.info(inst.getId()); BaseAlumni v = this.importExportSrv.convert(inst); v.setId(IdKit.uuid()); v.setCreateTime(new Date()); v.setLastUpdate(new Date()); this.baseAlumnidDao.save(v); this.baseAlumniImportSrv.deleteById(inst.getId()); count++; } return count; }

Result diagram demonstration:

How to import excel files in java

How to import excel files in java

How to import excel files in java

How to import excel files in java

Recommended related articles and tutorials:Java zero-based introduction

The above is the detailed content of How to import excel files in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn