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<List<Object>> 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<BaseAlumniImport> importList = this.baseAlumniImportSrv.findAll(); for (int i = 0; i < importList.size(); i += 10) { List<BaseAlumniImport> 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<BaseAlumniImport> 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<BaseAlumniImport> 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:
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!

The article discusses various Java garbage collection algorithms (Serial, Parallel, CMS, G1, ZGC), their performance impacts, and suitability for applications with large heaps.

The article discusses the Java Virtual Machine (JVM), detailing its role in running Java programs across different platforms. It explains the JVM's internal processes, key components, memory management, garbage collection, and performance optimizatio

Java's Nashorn engine enables JavaScript scripting within Java apps. Key steps include setting up Nashorn, managing scripts, and optimizing performance. Main issues involve security, memory management, and future compatibility due to Nashorn's deprec

Java's try-with-resources simplifies resource management by automatically closing resources like file streams or database connections, improving code readability and maintainability.

Java enums represent fixed sets of values, offering type safety, readability, and additional functionality through custom methods and constructors. They enhance code organization and can be used in switch statements for efficient value handling.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Zend Studio 13.0.1
Powerful PHP integrated development environment

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver CS6
Visual web development tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.