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<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!

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.
