In my previous blog <<itoo project actual combat to reduce IO read and write the idea of import >> I showed you how to do an Excel import that reduces IO read and write, and here I share specific code implementations:
I'll share it in the order of this picture.
Check that the Excel data is duplicated code:
<span style= "Font-family:times New roman;font-size:18px;" >//2. Look for duplicate rows from the specified column for (int i = 1; i < realRows-1; i++) {int nullcols = 0;//Use the non-repeating characteristics of the set element to determine if there are duplicate rows set<integer> Sameset = new hashset<integer> (); for (int j = 0; J < Uniquefields.length; J + +) {String currentcontent = uniquece Lls[j][i].getcontents (); Cell Samecell = Sheet.findcell (Currentcontent,uniquecells[j][i].getcolumn (), Uniquecells[j][i].getrow () + 1, Uniquecells[j][i].getcolumn (), Uniquecells[j][realrows-1].getrow (), true); if (Samecell! = null) {nullcols++; Sameset.add (Samecell.getrow ());}} if (Nullcols = = Uniquefields.length && sameset.size () = = 1) {throw new Excelexception ("There are duplicate lines in Excel, check");}}} </span>
Check to see if Excel data already exists in database:
<span style= "Font-family:times New roman;font-size:18px;" >for (int i = 1; i < realrows; i++) {//new object to be converted T entity = entityclass.newinstance ();//Query object based on business primary key Linkedhashmap<o Bject, object> uniquemap = new Linkedhashmap<object, object> (); String envalue = ""; for (int m = 0; M < uniquefields.length; m++) {//Gets the English text segment name string enname = Combinemap.get (Uniquefields[m]);//Gets the English text segment value//1. Get column number int col = colmap.get (uniquefields[m]) ;//2. Get content Envalue = Sheet.getcell (col, i). getcontents (). toString (). Trim (); Field field = NULL; field[] fields = Entityclass.getdeclaredfields (); Gets all the attributes in the subclass if (Arrays.aslist (Fields). Contains (Enname)) {//Determines whether the passed in attribute belongs to the self field = Entityclass.getdeclaredfield ( Enname); Get the properties of the class through reflection: else{class<t> FirstClass = Entityclass;firstclass = (class<t>) firstclass.getsuperclass (); field = Firstclass.getdeclaredfield (Enname);} Field.setaccessible (TRUE);//The value of the list object is first removed by reflection, and then compared to determine whether a for (int j = 0; J < Queryalllist.size (); k + +) is already present in the database Object FielDvalue = Field.get (Queryalllist.get (j));//If the object already exists, add it to the Error list, and Continueif (Fieldvalue.equals (envalue) && Fieldvalue!=null) {//Adds the row to the Error List errormap.put (I, "Object already exists"); continue;}} </span>
To process data that contains a primary foreign key relationship:
<span style= "Font-family:times New roman;font-size:18px;" >//is used to mark whether there is an empty reference object, Boolean isrefernull = false;//If there is a reference field, assign a value to the Reference field if (Referfieldmap! = null && Referfieldmap.size ()! = 0) {//Assign a value to the object's Reference field for (Entry<linkedhashmap<string, Class<?>>, linkedhashmap< String, string>> Entry:referFieldMap.entrySet ()) {linkedhashmap<string, class<?>> KeyMap = Entry.getkey (); Gets the entity foreign key name linkedhashmap<string, string> valueMap = entry//foreign key corresponding to the class. GetValue ();//Gets the Reference field name and type String Referfield = "" ; Class<?> type = null; Define the foreign key to one of the classes for (entry<string, class<?>> keyEntry:keyMap.entrySet ()) {Referfield = Keyentry.getkey ();//Required The foreign key attribute of the object to be imported type = Keyentry.getvalue (); The foreign key corresponds to the class}string Enfield = ""; field in Excel that has a foreign key relationship string Cnfield = ""; database field name corresponding to the class name in Excel String content = ""; for (entry<string, string> valueEntry:valueMap.entrySet ()) {Enfield = Val Ueentry.getvalue ();//field with foreign key relationship in Excel Cnfield = Valueentry.getkey (); int col = Colmap.get (cnField); content = Sheet.getcell (col, i). getcontents (). toString (). Trim (); Gets the contents of the cell corresponding to the foreign key}boolean isobjectbe = false; Determine if the reference object represented by the business primary key exists//list becomes map startobject fieldidvalue = ""; Object fieldnamevalue = "";//Place the value in the list in map field FieldID = NULL; Field FieldName = null;try {fieldName = Type.getdeclaredfield (enfield);//through reflection, gets the properties of the class name} catch (Nosuchfieldexception E 1) {e1.printstacktrace ();} catch (SecurityException E1) {e1.printstacktrace ();} Attribute namefieldname.setaccessible (TRUE); The setting can access the private property for (; Type! = Object.class; type = Type.getsuperclass ()) {try {FieldID = Type.getdeclaredfield ("id");// Gets the property ID of the class} catch (Exception e) {}}fieldid.setaccessible (true); String Linkkey = ""; for (entry<string, list> listEntity:listFileMap.entrySet ()) {Linkkey = Listentity.getkey (); List ListValue = Listentity.getvalue (), if (Linkkey! = "" "&& Linkkey.equals (Referfield)) {//To determine the current loop of foreign key properties and the KE in map Y values are consistent map<object, object> filemap = new Hashmap<object, object> (); Put attribute value for (int k = 0; k < listvalue.size (); k++) {try {fieldidvalue = Fieldid.get (Listvalue.get (k));//Get the value of id fieldnamevalue = Fieldname.get (Listvalue.get (k)); Get Name Value} catch (illegalargumentexception| Illegalaccessexception e) {e.printstacktrace ();} Filemap.put (Fieldidvalue, Fieldnamevalue); if (fieldnamevalue! = null& fieldnamevalue.tostring (). Equals (content) {//To determine if the contents of the cell exist//assigned to the Entity object Setfieldvaluebyname (Referfield,listvalue.get (k), entity) in the list; isobjectbe = True;}}} If the reference object is not empty, the object is assigned a value of if (isobjectbe = = False) {Isrefernull = True;errormap.put (i, "the reference object represented by the business primary key does not exist"); </span>
To save the data to the list in the behavior unit:
<span style= "Font-family:times New roman;font-size:18px;" >/** * @MethodName: Setfieldvaluebyname * @Description: Assign values to the fields of the object based on field name * @param fieldName * Field name * @param fi Eldvalue * Field value * @param o * object */private void Setfieldvaluebyname (String fieldName, Object Fieldvalu E,object o) throws Exception {Field field = Getfieldbyname (FieldName, O.getclass ()); if (Field! = null) {FIELD.SETACCESSIBL E (TRUE);//Gets the field type class<?> FieldType = Field.gettype ();//assigns a value to a field based on the field type if (String.class = = FieldType) {field.set (O, String.valueof (Fieldvalue));} else if ((Integer.type = = FieldType) | | (Integer.class = = FieldType)) {Field.set (O, Integer.parseint (fieldvalue.tostring ()));} else if ((Long.type = = FieldType) | | (Long.class = = FieldType)) {Field.set (O, long.valueof (fieldvalue.tostring ()));} else if ((Float.type = = FieldType) | | (Float.class = = FieldType)) {Field.set (O, float.valueof (fieldvalue.tostring ()));} else if ((Short.type = = FieldType) | | (Short.class = = Fieldtype) {field.set (O, short.valueof (fieldvalue.tostring ()));} else if ((Double.type = = FieldType) | | (Double.class = = FieldType)) {Field.set (O, double.valueof (fieldvalue.tostring ()));} else if (Character.type = = FieldType) {if (fieldvalue! = null) && (fieldvalue.tostring (). Length () > 0)) {field. Set (O,character.valueof (Fieldvalue.tostring (). CharAt (0)));}} else if (Date.class = = FieldType) {field.set (O, New SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"). Parse (fieldvalue.tostring ( )));} else {field.set (o, Fieldvalue);}} else {throw new Excelexception (O.getclass (). Getsimplename () + "class does not exist field name" + FieldName);}} </span>
The code also reflects a person's way of thinking, you want to read someone else's code, you need to do is how to let others read their own code. Recently learned a good way to read someone else's code, and share with you, when looking at someone's code, do not plunge into the first, And then I can't get out of it. First draw a picture of the code from the macro, and then follow this map to code, the whole block of code to read, the details need to be studied, so you will feel that reading other people's code is also a relaxed thing.
The above code is only part of the code, the complete code can be downloaded here:
Excelutil.java
"Java" Itoo project actual combat optimization after the specific code