Java implementation of Excel import Data tool class _java

Source: Internet
Author: User
Tags getmessage

The tool class that imports the Excel data, the call also has a few lines of code, very simple.

Copy Code code as follows:

Import JXL. Cell;
Import JXL. Sheet;
Import JXL. workbook;
Import jxl.read.biff.BiffException;
Import Org.apache.commons.beanutils.BeanUtils;
Import Org.slf4j.Logger;
Import Org.slf4j.LoggerFactory;

Import java.io.IOException;
Import Java.io.InputStream;
Import java.util.*;

/**
* Excel imported Tool class.
*/
public class Excelutils {
private static final Logger Logger = Loggerfactory.getlogger (Excelutils.class);
Success
public static final Integer STATUS_OK = integer.valueof (1);
Failed
public static final Integer status_no = integer.valueof (0);
/**
* Privatisation Builder
*/
Private Excelutils () {

}

/**
* Get the Data objects in Excel files
*
* @param is Excel
* @param excelcolumnnames The English name of each field in Excel (should be consistent with the Pojo object's field name, in order with Excel)
* @return Excel per row is a list of records, map is the corresponding "field name--> value"
* @throws Exception
*/
public static list<map<string, string>> Getimportdata (InputStream is, list<string> excelColumnNames ) throws Exception {
Logger.debug ("inputstream:{}", is);
if (is = = null) {
return Collections.emptylist ();
}

Workbook workbook = null;
try {
Get Excel
Workbook = Workbook.getworkbook (IS);
catch (Biffexception e) {
Logger.error (E.getmessage (), E);
return collections.empty_list;
catch (IOException e) {
Logger.error (E.getmessage (), E);
return collections.empty_list;
}
Logger.debug ("workbook:{}", workbook);

if (workbook = = null) {
return Collections.emptylist ();
}

       //First Sheet
        Sheet Sheet = workbook.getsheet (0);
       //number of rows
        int rowcounts = Sheet.getrows ()-1;
        logger.debug ("rowcounts:{}", rowcounts);
        list<map<string, string>> List = new arraylist<map< String, string>> (rowCounts-1);

Double for loop fetch data
for (int i = 1; i < rowcounts; i++) {
map<string, string> params = new hashmap<string, string> ();
I,j I: Rows j: Columns
for (int j = 0; J < Excelcolumnnames.size (); j + +) {
Cell cell = Sheet.getcell (j, I);
Params.put (Excelcolumnnames.get (j), Cell.getcontents ());
}

List.add (params);
}

        return list;
   }

   /**
     * Get Import data As object's list
     *
      * @param data
     * @param clazz
     * @param Excelcolumnnames
     * @param checkexcel
     * @param <t>
     * @return
     * @throws Exception
     */
    public static <T> list<t> makedata (list<map<string, string>> data, Class<t> Clazz, list<string> excelcolumnnames, Checkexcel checkexcel) throws Exception {
  & nbsp;     if (data = null | | data.isempty () | | | clazz = NULL | | checkexcel = = NULL) {
  & nbsp;         return collections.empty_list;
       }

        list<t> result = new Arraylist<t> (Data.size ());
        for (map<string, string> d:data) {
             if (checkexcel!= null &&!checkexcel.check (d)) {
                 continue;
           }
            T entity = clazz.newinstance ();
            for (String column:excelcolumnnames) {
                Beanutils.setproperty (Entity, column, D.get (column));
           }

Result.add (entity);
}

return result;
}
}

Check that the data in each row in Excel is legitimate

Copy Code code as follows:

Import Java.util.Map;
/**
* Check whether the data in Excel is valid for each row
*/
Public interface Checkexcel {
/**
* Return True Valid
*
* @param data in every row in data Excel
* @return
*/
public boolean check (map<string, string> data);
}

Call part

Copy Code code as follows:

list<map<string, string>> data = Excelutils.getimportdata (is,constants.excel_column_names);
list<feeallocation> allocations = excelutils.makedata (data, Feeallocation.class, Constants.excel_column_names , new Checkexcel () {
public boolean check (map<string, string> data) {
if (Stringutils.isempty (Data.get ("name"))
return false;
return true;
}
});

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.