Este artículo describe principalmente el proceso de cargar Excel bajo el marco SpringBoot-Mybatis e importarlo a la base de datos MySQL. Si la ID de usuario ya existe, actualice y modifique la información en la base de datos. Dado que se utiliza la tecnología de separación frontal, el registro principal de la parte Java de back-end es la interfaz de fondo. Puede implementar funciones conectándose con la interfaz front-end y usar marcos front-end como Layui para conectarse con ella. También puede escribir código de front-end usted mismo. Este artículo comienza con el controlador y comienza con el proceso de introducción, que incluye la conversión de la tabla del diccionario.
1. Annotaciones de importación en el archivo pom.xml, principalmente utilizando POI
<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.9</version> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency> <dependency> <MoupRoD> Commons-io </proupId> <artifactid> commons-io </artifactid> <versión> 2.4 </versión> </pendency>
2. Interfaz del controlador
@PostMapping ("/Save") public String addUser (@RequestParam ("archivo") archivo multipartfile) {string filename = file.getOriginalFileName (); intente {return sysService.batchImport (nombre de archivo, archivo); } Catch (MyException e) {E.PrintStackTrace (); return E.getMessage (); } catch (Exception e) {E.PrintStackTrace (); devolver "Excepción de archivo, importar fallado"; }}3. Interfaz de capa de servicio
Importación booleana (nombre de archivo de cadena, archivo multipartfile) arroja excepción;
4. Clase de implementación de la capa de negocios
@TransActional (readOnly = false, Rollbackfor = Exception.class) @Override public boolean Import (String FileName, MultipartFile) lanza Exception {MAP <String, Integer> departammap = finddepartment (); Map <string, integer> rolEmap = findrole (); boolean nonlull = false; List <Serem> UserList = New ArrayList <Seremower> (); if (! FileName.matches ("^.+//. (? I) (xls) $") &&! FileName.matches ("^.+//. (? I) (xlsx) $")) {tirar nueva myException ("El formato de archivo de carga es incorrecto"); } boolean isexcel2003 = true; if (filename.matches ("^.+//. (? i) (xlsx) $"))) {isexcel2003 = false; } InputStream IS = file.getInputStream (); Libro de trabajo wb = nulo; if (isexcel2003) {wb = new HSSFWorkBook (is); } else {wb = new XSSFWorkBook (is); } Hoja = wb.getSheetat (0); if (hoja! = null) {noTNull = true; } Usuario de usuario; for (int r = 1; r <= sheet.getLastrownum (); r ++) {fila fila = sheet.getrow (r); if (fila == null) {continuar; } user = new User (); if (row.getCell (0) .getCellType ()! = 1) {tire nueva myException ("import fallado (fila"+(r+1)+"y el formato de celda de identificación se establece en formato de texto)"); } String id = row.getCell (0) .getStringCellValue (); if (id == null || id.isEmpty ()) {tire nueva myException ("importar fallida (fila"+(r+1)+"e id no llena)"); } Name de cadena = row.getCell (1) .getStringCellValue (); if (name == null || name.isEmpty ()) {throw new myException ("import fallado (línea"+(r+1)+"y el nombre no se llena)"); } String department = row.getCell (2) .getStringCellValue (); if (departammap.get (departamento) == null) {tire nueva myException ("importar fallas (línea"+(r+1)+"y esta unidad no existe o la unidad no se llena)"); } Cadena rol = Row.getCell (3) .getStringCellValue (); if (rolEmap.get (rol) == null) {throw new myException ("importar fallido (línea"+(r+1)+", este rol no existe o el rol no se completa)"); } Fecha fecha; if (row.getCell (4) .getCellType ()! = 0) {tire nueva myException ("import fallida (línea"+(r+1)+", el formato de fecha de entrada es incorrecto o no se llena)"); } else {date = row.getCell (4) .getDateCellValue (); } user.setId (id); user.setName (nombre); user.setDePartmentId ((int) departammap.get (departamento)); user.setRoleId ((int) rolEmap.get (rol)); user.setDate (fecha); UserList.Add (usuario); } para (usuario de usuario: userList) {String id = user.getID (); int cnt = usermapper.selectById (id); if (cnt == 0) {usermapper.adduser (usuario); } else {usermapper.UpdateUserById (usuario); }} return NotNull; }Resumir
Lo anterior es lo que te presenta el editor. SpringBoot carga Excel e importe los datos de la tabla en o actualiza la base de datos MySQL. Espero que sea útil para todos. Si tiene alguna pregunta, déjame un mensaje y el editor responderá a todos a tiempo. ¡Muchas gracias por su apoyo al sitio web de Wulin.com!