Este artículo comparte la importación por lotes de los datos de la tabla de Excel en Java para su referencia. El contenido específico es el siguiente: importar java.awt.color; import java.io.bytearrayInputStream; import java.io.bytearrayOutputStream; import java.io.file; import java.io.fileInputStream; import java.io.inputstream; import java.lang.reflect.field; import java.text.dateformat; import java.text.DecimalFormat; import java.text.simpledateFormat; import java.util.*; import javax.swing.text.attributeset; import javax.swing.text.element; import javax.swing.text.html.css; import javax.swing.text.html.htmlDocument; import javax.swing.text.html.htmleditorkit; import cn.vrview.dev.common.exception.buseSException; importar org.apache.commons.lang3.stringutils; importar org.apache.logging.log4j.logmanager; importar org.apache.logging.log4j.logger; importar org.apache.poi.hssf.usermodel.*; importar org.apache.poi.hssf.util.hssfcolor; importar org.apache.poi.ss.usermodel.*; importar org.apache.poi.ss.util.cellrangaaddress; importar org.apache.poi.xssf.usermodel.xssfcolor; importar org.apache.poi.xssf.usermodel.xssffont; importar org.apache.poi.xssf.usermodel.xssfworkbook; importar org.springframework.web.util.htmlutils; import cn.vrview.dev.common.util.stringutil; clase pública ExcelTools { / ** log* / private static logger log = logManager.getLogger (); /** * Exportar Excel * <P> * Uso: <br> * <code> List <Map <String, Object >> DataList = New ArrayList <Map <String, Object >> (); <br> * IS = ExcelTools.ExportXLS (DataList, New String [] {"CreateTime: Date", "Nombre:" Nombre ", Sexo: Género", "," Observación: VENTA "}); * </code> * * @param recopilar * recopilación de datos que se exportará * @param encabezado * columna para exportarse * @return inputStream de retorno de retorno transmisión */ public static inputStream exportxls (colección <map <string >> coleccionar, string [] header) {byteArAteutPutStReam out = new byTearRauteutStream (); HSSFWorkBook Book = new HSSFWorkBook (); Pruebe {// Agregar una hoja HSSFSheet Hoja = Book.CreateSheet ("Hoja1"); // Definir el conjunto de nombres de columna que se exportarán Set <String> columns = new Hashset <String> (); // Establecer el color de fondo celular HSSFCellStyle CellStyle = Book.CreateCellStyle (); CellStyle.SetFillPattern (hssfcellstyle.solid_foreground); CellStyle.SetFillForeGroundColor (new hssfcolor.yellow (). getIndex ()); // Generar encabezado hssfrow row = sheet.createrow (0); HSSFCell Cell = Row.CreateCell (0); Cell.SetCellStyle (CellStyle); Cell.SetCellValue ("secuencia"); // El número de columna comienza desde 1 int n = 1; // Cadena de encabezado de analizador para (String Str: Header) {String [] arr = str.split (":"); columns.Add (n + "," + arr [0]); // Agregar el nombre de campo para exportar y unir al número de columna n celda = fila.createCell (n); Cell.SetCellStyle (CellStyle); Cell.SetCellValue (arr [1]); n ++; } // Generar filas de datos a partir de 1, 0 es el encabezado int i = 1; // Generar filas de datos para (Map <String, Object> Map: Collect) {HSSFROW DatoROW = Sheet.Createrow (i); // Generar el número de secuencia dataRow.CreateCell (0) .SetCellValue (i); // Generar otras columnas para (columna de cadena: columnas) {// Use comas para obtener el nombre del campo, [0] es el número de columna que corresponde al encabezado del encabezado. String columnName = column.split (",") [1]; // Generar el número de secuencia columna Cell = datarow.createCell (integer.parseInt (column.split (",") [0])); Valor de cadena = ""; valor = map.get (columnName) + ""; // Convertir a "" if ("null" .equals (valor)) {value = ""; } RichTextString RichTextString = Processhtml (libro, valor); Cell.getCellStyle (). SetWrapText (falso); Cell.SetCellValue (RichTextString); } i ++; } book.write (out); out.close (); } catch (Exception e) {E.PrintStackTrace (); } return new byteArrayInputStream (out.tobytearray ()); } /** * Obtenga datos de archivo de Excel <br> * Uso: <br> * SheetInfo SheetInfo = new ExecTools (). New SheetInfo (); <br> * SheetInfo.SetrowTitle (0); List <String> sheets = new ArrayList <String> (); <br> * String SheetName = "Sheet1"; sheets.add (sheetname); <br> * sheetInfo.setSheetNames (sábanas); <br> * sheetInfo.setColumnsMapping(new String[] { "prodName:Product Name", * "prodSpec:Specification", "collectPrice:Price:" + {@link RegExpEnum} * RegExpEnum.NOTEMPTY_ISNUMBER, "priceUnit:Unit", "collectMarket:quotation market", * "prodLevel:level" }); <br> * map <string, list> data = ExcelTools.getExcel (nuevo archivo (ruta), sheetInfo); * * @param * * @param sheetInfo * Información de inicialización * @return map {sheet1: list} * @throws Exception * Exception */ @SupessWarnings ("RawTypes") Map Public Static GetExcel (File F, SheetFo SheetFo, String ExcelType) Exception {return GetExCel (nuevo FileInputam (F), SheetInfo, String ExcelType) Exception {return GetExcel (nuevo FileInputam (F), SheetInfo, ExcelType). } @SupplesSwarnings ({"RawTypes", "sin verificar"}) Mapa estático público getExcel (inputStream in, sheetfo sheetInfo, string ExcelType) lanza la excepción {map <string, string> columnsmap = new HashMap <String, String> (); // Lista de mapas de expresión de verificación de columna <String> errmsg = new ArrayList <String> (); int errnum = 0; // Número total de errores int errlimit = 10; // limita el número de indicaciones de error/ ** Se usa para almacenar todos los contenidos que Excel lee de acuerdo con las reglas especificadas*/ map Excelfo = new Hashmap (); Libro de libros de trabajo = nulo; intente {if (Exceltype.equals ("xls")) {book = new HSSFWorkBook (in); // tirar nueva BusinessException ("La versión de Excel es demasiado baja, use la versión 2007 o superior (Extensión: XLSX)"); } else {book = new XSSFWorkBook (in); }} Catch (OutOfMemoryError e) {Throw New RuntimeException ("El archivo de Excel actual es demasiado grande, verifique si hay datos vacíos no válidos en cada tabla de hoja, incluidos los datos de fila y columna con formato y margen de alambre, elimine estos datos inválidos del archivo de Excel! } // checktitle (libro, sheetInfo); // Obtenga el número de hojas de trabajo int sheetnum = sheetInfo.getSheetNames (). Size (); // bucle todas las hojas de trabajo y lea los datos adentro para (int sheetEx = 0; sheadindex <sheetnum; sheetindex ++) {// Obtenga la hoja de trabajo actual String String Sheet = htmlutils.htmlunescape (sheetInfo.getSheetNames (). Get (SheetIndex)); Map <string, string> validateMap = new Hashmap <String, String> (); for (string mapstr: sheetfo.getColumnsMapping (). get (sheetName)) {string [] arr = mapstr.split (":"); columnsmap.put (arr [1], arr [0]); if (arr.length == 3) {// Si la expresión de verificación no está vacía, agrégalo al mapa a validateMap.put (arr [1], arr [2]); }} Hoja = book.getSheet (SheetName); if (null == hoja) {lanzar nueva runtimeException (String.format ("No se pudo obtener la tabla, confirme si la hoja"%s "existe en Excel", SheetName)); } // utilizado para almacenar el contenido de datos en la hoja de trabajo de la hoja de listas = new ArrayList (); // Obtener el número de filas en la tabla actual int file = sheet.getLastroWnum (); // Obtenga el número de columnas en la tabla actual int columnas = sheet.getrow (sheetInfo.getRowtitle ()). GetLastCellNum (); if (fila <= sheetinfo.getrowtitle ()) {// Si la tabla actual no tiene los datos requeridos, continúe el siguiente bucle; } // Obtenga la lista actual de contenido de título de la hoja de trabajo <String> titLelist = new ArrayList <String> (); // bucle cada celda en cada fila y lea el valor en la fila de celda titlerow = sheet.getrow (sheetinfo.getrowtitle ()); for (int jj = 0; jj <columnas; jj ++) {celular celular = titlerow.getCell (jj); if (CellTitle! = NULL) {int row = cellTitle.getRowIndex (); int columna = CellTitle.getColumnIndex (); if (isMergedRregion (hoja, fila, columna)) {titlelist.add (getMergedRregionValue (hoja, fila, columna)); } else {titlelist.add (getCellValue (Celltitle)); }} else {Throw New RuntimeException ("Error de lectura del encabezado de tabla, actualmente configurado en" Th " + (sheetInfo.getRowTitle () + 1) +" fila <br/> El contenido del encabezado de la tabla es: " + titlerow +", verifique si es correcto. Si hay una excepción, puede delerar el formato del encabezado y reastar el encabezado! ");} System.out.println (Titlelist); (StringUtils.delEtewhitespace (t) .equalsignorecase (colarr [1])) {include = true; (int i = sheetfo.getRowTitle () + 1; i <= Rows; i ++) {map rowmap = new HashMap (); <columnas; columnsmap.keyset ()) {if (stringUtilss.deletewhitespace (columntitle) .equalsignorecase (title)) {columnmapping = columnsmap.get (title) (Exceltype.equals ("xls")) {hssfcolor color = (hssfcolor) cellStyle.getFillForeGroundColorColor () color = (xssfcolor) CellStyle.getFillForeGroundColorColor (); 0 &&! Cell.getCellComment ()! = NULL) {//system.out.println(columnMapping+"@comment:"+cell.getCellComment (). ""; (. [" + validateRegmsg +"] </br>/n ");}}} else {if (stringUtil.isEmpty (columnMapping)) {continúa;} else {// int fila = cell.getrowindex (); /// int columna = cell.getColumnIndex (); // if (isMergedRegion (sheet, columna)) GetMergedRegionValue (shita, fila, columna)); > errlimit) {errmsg.add ("La plantilla de datos que importó es demasiado error de formato (total" + errnum + ", por favor verifique cuidadosamente si los datos de la plantilla son correctos!") RuntimeException ("test"); errmsg = new ArrayList <String> (); == 3) {// La expresión de verificación no está vacía, agregue el mapa a validateMap.put (arr [1], arr [2]); de hojas de trabajo int sheetnum = book.getNumberOfSheets (); de las filas int intse = sheet.getLastroWnum (); (columnas! = sheetInfo.getColumnsMapping (). get ("columnas"). longitud) {throw new BusinessException ("El formato de archivo es incorrecto, vuelva a seleccionar o descargar la plantilla") Incorrecto, vuelva a seleccionar o descargue la plantilla ");} // Obtenga la lista actual de contenido de contenido del título de la hoja de trabajo <String> titLelist = new ArrayList <String> (); // bucle cada celda en cada fila y lea el valor en la celda para (int jj = 0; jj <columnas; jj ++) {titelist.addd (titlerow.getCell (jj) (jj). } // Verifique la cadena de encabezado de tabla [] títulos = sheetfo.getColumnsMapping (). Get ("columnas"); "Tabla '" + S // + "' La columna no existe!"); Hashmap (); GetCellValue (celda); .get (columntitle); Errmsg.Add ("th" + i + "línea: [" + columntitle + "] Los datos son:" + value.trim () + "'no coincide! Excelinfo.put (sheet.getSheetName (), sheetList); tirar nueva runtimeException (errmsg.ToString (). replaceAll ("// [| //]", "")); El título se encuentra, la línea de inicio es 0, no 1*/ private int rowtitle = 1; no está definido, el valor predeterminado se dio "sheet1" if (null == sheetnames || sheetnames.size () == 0) {this.sheetnames.add ("sheet1"); sheetnames.size () == 0) {sheetnames.add ("sheet1"); setColumnsMapping (map <string, string []> columnsmapping) {this.columnsmapping = columnsmapping; 1:43:24 pm*@since: 1.0*/public enum regexpenum {/** no vacía*/notempty ("no se puede estar vacío", "(? "// d+"); Hssfworkbook * @param html * @return richtextString */ @supesswarnings ("no usado") privado richtextString processhtml (hssfworkbook wb, string html) {richtextString rt = null Kit.CreateDefaultDocument (); SB.Append ('/n'); fragment.getendoffset () - frag.getStarToffSet ()); LastPos <Doc.getLength (); Fragment); @return font * @throws Exception */ private static font getFontFromFragment (Workbook WB, Element Fragment) lanza la excepción {font font = wb.createFont () ae.nextelement (); ((Xssffont) Font) .SetColor (new XSSFColor (c)); c.getGreen (), c.getBlue ()); Font.setBoldweight (Font.BoldWeight_Bold); CA = SHOE.GetMergedRegion (i); (Cell.getColumnIndex () <= Lastc && Cell.getColumnIndex ()> = FirstC) {if (Cell.getRowIndex () == Firstr) {return lastr - Firstr; GetMergedRegionValue (Hoja, int Row, int Column) FirStrow = CA.GetFirStOW (); return null; CellRangoDdress Range = Sheet.getMergedRegion (i); LastColumn) {return true; fila* @param lasstrow* end fila* @param firstcol* Inicio columna* @param LastCol* End Column*/ @supplesswarnings ("sin usar") private void Mergeregion (hoja de hoja, int firstrow, int Lastrow, int FirstCol, int FirstCol) {hoja). } / ** * Obtenga el valor de la celda * * @param celular * @return * / public static string getCellValue (celular) {if (celular == null) return ""; Cell.Cell_Type_Boolean) {return String.ValueOf (Cell.getBooleanCellValue ()); (HssfdateUtil.IscellDateFormatted (celular)) {// Formato de fecha y formato de tiempo SimpledAnFormat SDF = new SimpleDateFormat ("yyyy-mm-dd"); == 31) {// Formato de fecha personalizada: yy año mm DD DD (resuelto juzgando la ID de formato de la celda, el valor de ID es 3 1) SimpleFormat SDF = new SimpleDateFormat ("yyyyy-mm-dd"); .getJavadate (valor); FilterStr (String Str) {str = str.replace (String.ValueOf ((char) 160), ""). System.out.println (convertrgbTox (hssfcolor.yellow.triplet)); Cadena estática convertrgbTox (corta [] rgb) {int r = rgb [0], g = rgb [1], b = rgb [2] == 10) rfString = "A"; == 10) RSString = "A"; String.Valueof (Rred); GFString = "E"; "D"; bfString = "B"; == 11) BSString = "B"; BSString; Mire la página de JS.JSP nuevamente
<body> <viv> <form id = "mainform" action = "$ {ctx}/bom/ciscaseAction/$ {action}" método = "post" enctype = "multipart/formy-data"> <input type = "file" name = "file"/> <a href = "$ {ctx}/static/case tempter.xate.xls" RELLE "RELLE" RELLE " TEMPLATE </a> </form> </div> <script type = "text/javascript"> $ (function () {$ ('#mainform'). form ({onSubMit: function () {var isValid = $ (this) .Form ('Validate'); return IsValid; // return False to termine formul }}); </script> </body>Interfaz principal JSP
Copie el código de la siguiente manera: <a href = "javaScript (0)" rel = "externo nofollow" sencillo = "true" icOncls = "icon-standard-application-go" onClick = "importation ()"> import </a>
// Importar función importation () {d = $ ("#dlg"). Dialog ({title: 'case import', width: 500, altura: 500, href: '$ {ctx}/bom/ciscasAction/importaction/', maximizable: true, modal: true, buttons: {{text: 'import', handler: function () {$ ('#('#). }}, {text: 'cancelar', handler: function () {d.panel ('cerrar'); }El efecto de hacer clic en la página es que hacer clic en importar saltará a la página de JSP
Mira la capa del controlador nuevamente
/ *** Página de importación*/ @RequestMapping (valor = "importación", método = requestmethod.get) public string importform (modelo modelo) {model.addattribute ("acción", "import"); return "System/ciscaseActionImoportForm"; } / *** import* / @RequestMapping (valor = "import", método = requestmethod.post) @ResponseBody public String importación (@RequestParam ("File") MultipartFile MultipartFile, Model Model) lanza la excepción {ciscaseActionservice.upload (multipartFile); devolver "éxito"; } Capa de servicio
/ *** Importar caso*/ @SupplesSwarnings ({"RawTypes", "sin verificar"}) public void upload (multipartfile multipartFile) lanza la excepción {inputStream inputStream = multipartfile.getInputStream (); ExcelTools exceltools = new ExtoLTools (); ExcelTools.SheetInfo SheetInfo = ExcelTools.new SheetInfo (); sheetinfo.setrowtitle (0); Columnas de mapa = new HashMap (); columns.put ("columnas", nueva cadena [] {"nombre: nombre del caso", "Violatelaw: Break of Law", "PunishBasis: PunishBasis"}); sheetInfo.setColumnsMapping (columnas); List <Hashmap <String, String >> mapList = ExcelTools.getExcel (InputStream, SheetInfo); for (int i = 0; i <maplist.size (); i ++) {hashmap <string, string> map = mapList.get (i); Name de cadena = map.get ("nombre"); if (stringUtils.isEmpty (name)) {throw New BusinessException ("th" + (i + 2) + "El nombre del caso no puede estar vacío"); } String ViolationLaw = map.get ("Violatelaw"); String PunisionBasis = map.get ("PunishBasis"); Ciscaseaction ciscaseaction = new CiscAseaction (); ciscAseAction.setName (nombre); ciscaseaction.setViolatelaw (Violatelaw); ciscaseaction.setPunishbasis (Punishbasis); this.insert (ciscaseaction); // llamando al método de inserción de la misma capa}} Lo anterior es todo el contenido de este artículo. Espero que sea útil para el aprendizaje de todos y espero que todos apoyen más a Wulin.com.