Cet article partage l'importation par lots de données de table Excel en Java pour votre référence. Le contenu spécifique est le suivant: Importer java.awt.color; Importer java.io.ByteArrayInputStream; Importer java.io.ByteArrayOutputStream; Importer 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. *; Importer javax.swing.text.attributeset; import javax.swing.text.element; import javax.swing.text.html.css; Importer javax.swing.text.html.htmldocument; Importer javax.swing.text.html.htmleditorkit; Importer cn.vrview.dev.common.exception.businessException; import org.apache.commons.lang3.stringutils; import org.apache.logging.log4j.logmanager; import org.apache.logging.log4j.logger; import org.apache.poi.hssf.usermodel. *; import org.apache.poi.hssf.util.hssfcolor; import org.apache.poi.ss.UserModel. *; import org.apache.poi.ss.util.cellRangeaddress; import org.apache.poi.xssf.usermodel.xssfcolor; import org.apache.poi.xssf.usermodel.xssffont; import org.apache.poi.xssf.usermodel.xssfworkbook; import org.springframework.web.util.htmlutils; import Cn.vrview.dev.common.util.stringutil; classe publique exceltools {/ ** log * / private static logger log = logManager.getLogger (); / ** * Exporter Excel * <p> * Utilisation: <br> * <code> Liste <map <string, objet >> datalist = new ArrayList <map <string, objet >> (); <br> * Is = exceltools.exportxls (datalist, new String [] {"Createtime: Date", "Name", "Sex: Gender", "Remark: Remark"}); * </code> * * @param Collect * Collection de données à exporter * @param henter * colonne à exporter * @return inputStream return File Stream * / public static inputStream exportxls (Collection <Map <String, objet >> collection, string [] header) {bytearrayoutPutStream out = new ByTayoutputStream (); HSSFWorkBook Book = new hssfworkbook (); essayez {// ajouter une feuille hssfsheet sheet = book.createTheet ("sheet1"); // Définissez l'ensemble des noms de colonnes à exporter <string> colonnes = new hashSet <string> (); // Définit la couleur de fond de cellule hssfCellStyle CellStyle = book.CreateCellStyle (); CellStyle.setFillPattern (hssfcellStyle.solid_foreground); CellStyle.setFillForegroundColor (new hssfcolor.yellow (). getIndex ()); // Générer l'en-tête hssfrow row = sheet.createrow (0); HSSFCELL CELLE = ROW.CREATECELL (0); Cell.SetcellStyle (CellStyle); Cell.SetCellValue ("séquence"); // Le numéro de colonne commence à partir de 1 int n = 1; // l'analyse de la chaîne d'en-tête pour (string str: en-tête) {String [] arr = str.split (":"); colonnes.add (n + "," + arr [0]); // ajouter le nom de champ pour exporter et se lier au numéro de colonne n cell = row.createCell (n); Cell.SetcellStyle (CellStyle); Cell.SetCellValue (ARR [1]); n ++; } // générer des lignes de données à partir de 1, 0 est l'en-tête int i = 1; // générer des lignes de données pour (map <string, objet> map: collection) {hssfrow datarow = sheet.createrow (i); // Générez le numéro de séquence Datarow.CreateCell (0) .SetCellValue (i); // Générez d'autres colonnes pour (colonne de chaîne: colonnes) {// Utilisez des virgules pour obtenir le nom de champ, [0] est le numéro de colonne à correspondre à l'en-tête. String Columnname = Column.Split (",") [1]; // Générez le numéro de séquence Column Cell = datarow.CreateCell (Integer.ParseInt (Column.Split (",") [0])); String value = ""; Value = map.get (Columnname) + ""; // Convertir en "" if ("null" .equals (value)) {value = ""; } RichTextString RichTextString = processHtml (livre, valeur); Cell.getCellStyle (). SetWrapText (false); Cell.SetCellValue (RichTextString); } i ++; } book.write (out); out.close (); } catch (exception e) {e.printStackTrace (); } return new bytearrayInputStream (out.toByTearray ()); } / ** * Obtenez des données de fichier Excel <br> * Utilisation: <br> * sheetInfo sheetInfo = new Exceltools (). New sheetInfo (); <br> * sheetInfo.setRowTitle (0); List <string> sheets = new ArrayList <string> (); <br> * String sheetname = "sheet1"; sheets.add (sheetname); <br> * sheetInfo.setheetNames (feuilles); <br> * sheetInfo.setColumnSmapping (new String [] {"prodname: nom de produit", * "prodSpec: Specification", "CollectPrice: Price:" + {@Link Regexpenum} * regexpenum.Notempty_isnumber, "Pricenit: unit"); <br> * map <string, list> data = exceltools.getExcel (nouveau fichier (chemin), sheetInfo); * * @param * * @param sheetInfo * Informations d'initialisation * @return Map {sheet1: list} * @throws exception * exception * / @SuppressWarnings ("RawTypes") Map statique publique GetExcel (fichier f, feuille de feuille de feuille de stress (F), FleatInfo, exclype (new fileInputtream (f), sheetinfo, exclype); } @SuppressWarnings ({"RawTypes", "Unchecked"}) Map statique publique GetExcel (InputStream in, sheetInfo sheetInfo, String ExcelType) lève exception {map <string, string> columnsmap = new Hashmap <String, string> (); // Colonne Vérification Expression Map List <string> errmsg = new ArrayList <string> (); int errnum = 0; // nombre total d'erreurs int errlimit = 10; // limiter le nombre d'invites d'erreur / ** Utilisé pour stocker tous les contenus que Excel lit en fonction des règles spécifiées * / map ExceLinfo = new HashMap (); Livre de travail = null; essayez {if (excelType.equals ("xls")) {book = new hssfworkbook (in); // lance New BusinessException ("La version Excel est trop faible, veuillez utiliser la version 2007 ou supérieure (extension: xlsx)"); } else {book = new XSSFWorkBook (in); }} Catch (OutOfMemoryError E) {Throw New RuntimeException ("Le fichier Excel actuel est trop grand, veuillez vérifier s'il y a des données vides non valides dans chaque table de feuille, y compris les données de ligne et de colonne avec le format et le wireframe, veuillez supprimer ces données invalides! Taille normale du fichier Excel [dans 1M]"); } // checkTitle (livre, sheetInfo); // Obtenez le nombre de feuilles de calcul int sheetnum = sheetInfo.getSheetNames (). Size (); // Loucle toutes les feuilles de calcul et lire les données à l'intérieur pour (int sheetIndex = 0; sheetIndex <egetnum; sheetIndex ++) {// Obtenez la chaîne d'objet de travail actuelle SheetName = htmlutils.htmlunescape (sheetInfo.getSheetNames (). Get (sheetIndex)); Map <string, string> validateMap = new hashmap <string, string> (); for (String MapStr: sheetInfo.getColumnSmapping (). get (sheetname)) {String [] arr = mapstr.split (":"); ColumnsMap.put (arr [1], arr [0]); if (arr.length == 3) {// Si l'expression de vérification n'est pas vide, ajoutez-la à la carte à validatemap.put (arr [1], arr [2]); }} Feuille de feuille = book.getSheet (sheetname); if (null == sheet) {lancez new RuntimeException (String.Format ("Échec de l'obtention du tableau, veuillez confirmer si la feuille"% s "existe dans Excel", sheetname)); } // Utilisé pour stocker le contenu des données dans la liste de feuilles de travail SheetList = new ArrayList (); // Obtenez le nombre de lignes dans la table actuelle intr lignes = sheet.getLastRowm (); // Obtenez le nombre de colonnes dans la table actuelle des colonnes int = sheet.getRow (sheetInfo.getRowTitle ()). GetlastCellnum (); if (lignes <= sheetInfo.getRowTitle ()) {// Si la table actuelle n'a pas les données requises, continuez la boucle suivante; } // Obtenez la liste de contenus du titre de la feuille de calcul actuelle <string> titlelist = new ArrayList <string> (); // boucler chaque cellule de chaque ligne et lire la valeur dans la ligne de cellule titlerrow = sheet.getRow (sheetInfo.getRowTitle ()); pour (int jj = 0; jj <colonnes; jj ++) {Cell CellTitle = titlerrow.getCell (jj); if (CellTitle! = null) {int row = CellTitle.getRowIndex (); int colmn = CellTitle.getColumnIndex (); if (ismergedRegion (feuille, ligne, colonne)) {titlelist.add (getMerGegeGionValue (feuille, ligne, colonne)); } else {titlelist.add (getCellValue (CellTitle)); }} else {lancez new RuntimeException ("l'erreur de lecture de l'en-tête de table, actuellement définie sur" th "+ (sheetInfo.getRowTitle () + 1) +" Row <br/> Le contenu de l'en-tête de la table est: "+ titlerrow +" System.out.println (titlelist); (StringUtils.DeleTewHitespace (T) .EqualSignoreCase (Colarr [1]) {include = true; Break; Titre pour (int i = sheetInfo.getRowTitle () + 1; i <= lignes; i ++) {map rowmap = new hashmap (); 0; (String Title: ColumnSmap.KeySet ()) {if (StringUtils.DeleTewhitespace (ColumnTitle) .EqualsInGorecase (title) {ColumnMapping = ColumnSmap.get (Title); Cell.GetCellStyle (); convertrgbtohex (Color.getTriplet ()));}} else {xssfcolor color = (xssfcolor) CellStyle.getFillFore filterstr (Cell + ""); int metrrow = getMerGedRegrow (feuille, cellule); RowMap.put ("Rowspan", Rowspan + ColumnMapping + "-" + Value + "-" + (MerGrow + 1));} if (Cell.getCellComment ()! = NULL) {//System.out.println(ColumnMapping + "@ comment:" + Cell.getCellComment (). Rowmap.put (ColnumnMapping + "@ commentaire", Cell.getCellComment (). GetString ()); EUM = regexpenum.valueof (validatemap.get (colonnes)); } else {errnum ++; (StringUtil.isempty (ColnumnMapping)) {Continuer;} else {// int row = Cell.getRowIndex (); Rowmap.put (ColumnMapping, valeur); Erreur de format (éléments totaux "+ errnum +"), veuillez vérifier attentivement si les données du modèle sont correctes! ");} lancez un nouveau RuntimeException (errmsg.toString (). RempaceALL (" // | //] "," "));} // if (true) lancez la nouvelle liste de runtimeException (" Test "); retour exceLinfo;} public STATIC LIST <SALLED> GetExcel (InputStream dans, sheetInfo sheetInfo) exception {map <string, string> columsmap = new hashmap <string, string> (); 10; // limite le nombre d'invites d'erreur pour (String MapStr: sheetInfo.getColumnSmapping (). Get ("colonnes")) {String [] arr = mapstr.split (":"); ValidateMap.put (Arr [1], arr [2]);}} / ** Utilisé pour stocker tous // Louit toutes les feuilles de travail et lisez les données pour (int sheetindex = 0; sheetdinex <eftNum; sheetIndex ++) {// Utiliser la feuille de travail actuelle Sheet = Book.getSheetAt (SheetIndex); des colonnes dans la table actuelle Titlerow = sheet.getRow (sheetInfo.getRowTitle ()); sheetInfo.getColumnSmapping (). get ("colonnes"). Length) {Throw New BusinessException ("Le format de fichier est incorrect, veuillez rééléquer ou télécharger le modèle"); Réélectionnez ou téléchargez le modèle ");} // Obtenez la liste de contenu du titre de la feuille de travail actuelle <string> titlelist = new ArrayList <string> (); // boucle chaque cellule de chaque ligne et lisez la valeur dans la cellule pour (int jj = 0; jj <Columns; JJ ++) {titlelist.add (Titlerow.gell (jj) .getStrsit La chaîne d'en-tête de table [] titres = sheetInfo.getColumnSmapping (). get ("colonnes"); // + "'La colonne n'existe pas!"); datarow = sheet.getRow (i); Le nom d'attribut entité correspondant à la colonne de cellule colonne ColumnMapping = ColumnSmap.get (colonnes); String validateReg = ""; .get (colonnes)); ErrLimit) {errmsg.add ("th" + i + "Line: [" + ColumnTitle + "] Les données sont:" "+ valeur.trim () +" 'ne correspond pas! } // excelinfo.put (sheet.getSheetName (), feuille);} dans.close (); Jetez un nouveau RuntimeException (errmsg.toString (). RempaceAll ("// | //]", ""); Le titre est situé, la ligne de départ est 0, pas 1 * / private int rowTitle = 1; SheetNames n'est pas défini, la valeur par défaut est donnée "sheet1" if (null == sheetNames || sheetNames.size () == 0) {this.sheetNames.add ("sheet1");} else {this.sheetNames = sheetNames; SheetNames.size () == 0) {SheetNames.Add ("Sheet1");}} public int GetrowTitle () {return RowTitle; setColumnsMapping (map <string, string []> ColumnSmapping) {this.columsMapping = ColumnSmapping;} public list <string> getSheetNames () {return sheetNames; @Date: 2013-12-2 1:43:24 PM * @Since: 1.0 * / public Enum Regexpenum {/ ** Not vide * / Nothempty ("Can't Be vide", "(?! + $). +"), / ** doit être un numéro * / isNumber ("Can't Be A Number", "/ d *"), / ** Not Empty et un numéro * / Not Amber_ et un nombre "," // d + "); / ** Texte * / Texte de chaîne privée; / ** Niveau * / Valeur de chaîne privée; Public String GetText () {return Text;} public String getValue () {return Value;} private regexpenum (String Text, String Value) {this.tex HSSFWORKBOOK * @param html * @return RichtextString * / @SuppressWarnings ("inutilisé") Private Static RichtextString ProcessHtml (HSSFWORKBOOK WB, String HTML) {RichtextString RT = null; Kit.CreateDefaultDocument (); SB.APPED ('/ n'); fragment.gettendoffset () - frag.getStartoffset ()); Doc.getLength (); RT.Applyfont (frag.getStartoffset () + Fragment.gettendOffset () + Font);}}} Catch (exception e) @Throws Exception * / Private Static Font GetFontFromFragment (Workbook WB, Element Fragment) exception {Font Font = WB.CreateFont (); AE.NextElement (); FONT) .setColor (nouveau XSSFColor (C)); c.getBlue ()); (hssffont) .setColor (col.getIndex ()); Retourne la police;} public static int getmergedRegrow (feuille de feuille, cellule) {// obtient le nombre de cellules fusionnées. Cellule, la ligne de démarrage, la colonne de fin Int Firstc = CA.getFiRSTCOLUM (); int lastc = CA.GetLastColumn (); Cell.getColumnIndex ()> = firstc) {if (Cell.getRowIndex () == firstr) {return lastr - firstr; sheetmegecount = sheet.getNummergedRegions (); pour (int i = 0; CA.getLastrow (); Une cellule fusionnée * * @param sheet * @param row * Row Indice de Row * @param colonne * COLUMNE INCLUSTRATION * @return * / public static boolean ismergedRegion (feuille de feuille, ligne int, colonne intraire) {int sheetmercoule = sheet.getNummerGegedRegions (); sheet.getMergedRegion (i); int premier. return true;}} return false;} / ** * Déterminez si la page de feuille contient des cellules fusionnées * * @param sheet * @return * / @suppresswarnings (inutilisé ") Lastrow * End Row * @Param FirstCol * Start Column * @param LastCol * END COLUMN * / @SUPPRESSWARNINGS ("UNUSE") Private Void MergeRegion (feuille de feuille, Int FirStrow, int Lastrow, Int Firstcol (Firestrow / ** * Obtenez la valeur de la cellule * * @param cell * @return * / public static static getCellValue (Cell cell) {if (cell == null) return ""; Cell.CELL_TYPE_BOOLEAN) {return String.Valueof (Cell.getBoolEanCellValue ());} else if (cell.getCellType () == Cell.Cell_Type_Formula) {return Cell.getCellFormula (); (HSSFDateUtil.iscellDateFormatt (Cell)) {// Format de date de gestion et de temps SimpledateFormat sdf = new SimpledateFormat ("Yyyy-mm-dd"); (Cell.getCellStyle (). GetDataFormat () == 31) {// Date personnalisée Format: Yy Year Mm Mois DD DAT (Résoudre en jugeant le format ID de la cellule, la valeur de l'ID est 3 1) SimpledateFormat SDF = New SimpledateFormat ("Yyyy-mm-dd"); Org.apache.poi.ss.Sullermodel.DateUtil .getJavadate (valeur); String.valueof (format.format (valeur));}} System.out.println (convertrgbtohex (hssfcolor.yell.triplet)); STATIC STATIQUE CONVERTrGBTOHEX (Croit [] RGB) {int R = RGB [0] == 10) RfString = "A"; == 10) RSSTRING = "A"; String.Valueof (Rred); gfString = "e"; else if (vert ==) gfString = "f"; "D"; else if (rgreen ==) gsstring = "e"; BFSTRING = "B"; Else (Blue == 12) BFSTRING = "C"; == 11) BSString = "B"; BSString; Résultat = RFString + GfString + BFString; Regardez à nouveau la page From.jsp
<body> <div> <form id = "mainform" action = "$ {ctx} / bom / ciscaseAction / $ {action}" method = "post" enctype = "multipart / form-data"> <entrée type = "file" name = "file" /> <a href = "$ {ctx} / static Importation wempl Template </a> </ form> </div> <script type = "text / javascript"> $ (function () {$ ('# mainform'). form ({onSubmit: function () {var isvalid = $ (this) .form ('valider'); return isvalid; // return false to Termine Form soumis });}); </cript> </ body>Interface principale jsp
Copiez le code comme suit: <a href = "javascript (0)" rel = "external nofollow" plain = "true" iconcls = "icon-standard-application-go" onclick = "importatation ()"> import </a>
// importation function importation () {d = $ ("# dlg"). Boîte de dialogue ({title: 'Case Import', Width: 500, Height: 500, href: '$ {ctx} / true, Bom / CiscaseAction / ImportAction', handler: fonction (fonction () {$ ('# principale'). }}, {text: 'annuler', handler: function () {d.panel ('close');}}]}); }L'effet de clic sur la page est que cliquer sur l'importation passera à la page From.jsp
Regardez à nouveau la couche de contrôleur
/ ** * Page d'importation * / @RequestMapping (value = "importation", method = requestMethod.get) public String ImportForm (modèle modèle) {modèle.addattribute ("action", "import"); return "Système / CiscasEActionImOportForm"; } / ** * import * / @requestmapping (value = "import", méthode = requestMethod.Post) @ResponseBody public String import retourner le "succès"; } Couche de service
/ ** * Importer Case * / @SuppressWarnings ({"RawTypes", "Unchecked"}) public void upload (multipartFile MultipartFile) lève exception {inputStream inputStream = multipartFile.getInputStream (); Exceltools exceltools = new exceltools (); Exceltools.sheetInfo sheetInfo = exceltools.new sheetInfo (); sheetInfo.setRowTitle (0); Map Columns = new HashMap (); ColumnS.put ("Columns", New String [] {"Name: Case Name", "Violatelaw: Break of Law", "PunishBasis: PunishBasis"}); sheetInfo.setColumnSmapping (colonnes); List <hashmap <string, string >> maplist = exceltools.getExcel (inputStream, sheetInfo); for (int i = 0; i <maplist.size (); i ++) {hashmap <string, string> map = maplist.get (i); String name = map.get ("name"); if (stringUtils.Isempty (name)) {Throw New BusinessException ("th" + (i + 2) + "Le nom du cas ne peut pas être vide"); } String violationLAW = map.get ("Violatelaw"); String punishingBasis = map.get ("punishBasis"); CiscaseAction CiscaseAction = new CiscaseAction (); CiscasEAction.SetName (nom); CiscaseAction.Setviolatelaw (Violatelaw); CiscaseAction.setpunishbasis (punishbasis); this.insert (CiscaseAction); // appelle la méthode d'insertion du même calque}} Ce qui précède est tout le contenu de cet article. J'espère que cela sera utile à l'apprentissage de tous et j'espère que tout le monde soutiendra davantage Wulin.com.