利用dbunit 进行单元测试

来源:互联网 发布:爬山算法 贪心算法 编辑:程序博客网 时间:2024/04/29 10:15

从数据库导出excel数据


import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.dbunit.database.AmbiguousTableNameException;
import org.dbunit.database.DatabaseConfig;
import org.dbunit.database.DatabaseConnection;
import org.dbunit.database.IDatabaseConnection;
import org.dbunit.database.QueryDataSet;
import org.dbunit.dataset.Column;
import org.dbunit.dataset.DataSetException;
import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.ITable;
import org.dbunit.dataset.ITableIterator;
import org.dbunit.dataset.ITableMetaData;
import org.dbunit.dataset.xml.FlatXmlDataSet;
import org.dbunit.ext.mysql.MySqlDataTypeFactory;

import com.sf.iec.common.util.DateUtil;
import com.sf.iec.common.util.PoiUtils;

public class ExportData2Excel {
    private final static String FILENAME ="d://dbtest//";

    /**
     * @param args
     */
    public static void main(String[] args) throws Exception {
        Connection conn = null;
        try {
//            conn = new DataSource().getConnection();
            Class.forName("com.mysql.jdbc.Driver");  
            conn = DriverManager.getConnection(  
                    "jdbc:mysql://10.0.137.17:3306/cbt?autoReconnect=true&" +
                    "useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull" +
                    "&transformedBitIsBoolean=true",
                    "root", "123456");
         
            IDatabaseConnection connection = new DatabaseConnection(conn);
            DatabaseConfig config = connection.getConfig();  
            config.setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY, new MySqlDataTypeFactory());
            QueryDataSet dataSet = new QueryDataSet(connection);
            //将整个atd_expensesclass表里的数据导出到 xml文件里  
            Map<String, String> tableMap = new HashMap<String, String>();
 
            tableMap.put("prc_sundry_changes", "");
            //把需要的表数据从数据库导入到excel
            exportExcelFromDataBase(connection, dataSet, tableMap);
            
        } catch (Exception e) {
            e.printStackTrace();
        }
        finally{
            if(null != conn)
            {
                conn.close();
            }
        }
    }


    /**
     * 按照表名导出多个EXCEL文件(sheet名为表名)
     * @param connection
     * @param dataSet
     * @param tableMap
     * @throws AmbiguousTableNameException
     * @throws IOException
     * @throws DataSetException
     * @throws FileNotFoundException
     */
    public static void exportExcelFromDataBase(IDatabaseConnection connection, QueryDataSet dataSet,
            Map<String, String> tableMap) throws AmbiguousTableNameException, IOException, DataSetException,
            FileNotFoundException {
        //导出到Excel文件里  
        /*注意这里导入了poi-3.2-FINAL.jar,在这里我用的dbunit-2.4.9.jar
         * 是最新的版本,而poi目前最新的版本是poi-3.10-beta2-20130904.jar,
         * 与dbunit的最新版本一起使用会报错 会出现:
         * java.lang.NoSuchMethodError: org.apache.poi.hssf.usermodel.HSSFCell.setCellValue(Lorg/apache/poi/hssf/usermodel/HSSFRichTextString;)V
         * 而换成poi-3.2-FINAL.jar时则成功导出,生成了两个Sheet,Sheet名为表名
         * 即只能导出一个表中的数据,并且只能导出Excel97-2003*.xls版本的文件
         * 而使用FlatXmlDataSet能够导出多个表中的数据
        */
        if(tableMap != null && !tableMap.isEmpty())
        {
            for(Entry<String, String> entry : tableMap.entrySet())
            {
                String tableName = entry.getKey();
                String queryStr = entry.getValue();
                QueryDataSet dataSet1 = new QueryDataSet(connection);
                if(StringUtils.isNotBlank(tableName))
                {
                    if(StringUtils.isNotBlank(queryStr))
                    {
                        dataSet1.addTable(tableName, queryStr);
                    }
                    else
                    {
                        dataSet1.addTable(tableName);
                    }
                    writeExcel(dataSet1, new FileOutputStream(FILENAME + tableName +".xls"));
                }
            }
        }
        
    }
    
    
    /**
     * 导出一个EXCEL文件(sheet名为表名)
     * @param connection
     * @param dataSet
     * @param tableMap
     * @throws AmbiguousTableNameException
     * @throws IOException
     * @throws DataSetException
     * @throws FileNotFoundException
     */
    public static void exportTotalExcelFromDataBase(IDatabaseConnection connection, QueryDataSet dataSet,
            Map<String, String> tableMap, String fileName) throws AmbiguousTableNameException, IOException, DataSetException,
            FileNotFoundException {
        //导出到Excel文件里  
        /*注意这里导入了poi-3.2-FINAL.jar,在这里我用的dbunit-2.4.9.jar
         * 是最新的版本,而poi目前最新的版本是poi-3.10-beta2-20130904.jar,
         * 与dbunit的最新版本一起使用会报错 会出现:
         * java.lang.NoSuchMethodError: org.apache.poi.hssf.usermodel.HSSFCell.setCellValue(Lorg/apache/poi/hssf/usermodel/HSSFRichTextString;)V
         * 而换成poi-3.2-FINAL.jar时则成功导出,生成了两个Sheet,Sheet名为表名
         * 即只能导出一个表中的数据,并且只能导出Excel97-2003*.xls版本的文件
         * 而使用FlatXmlDataSet能够导出多个表中的数据
        */
        if(tableMap != null && !tableMap.isEmpty())
        {
            for(Entry<String, String> entry : tableMap.entrySet())
            {
                String tableName = entry.getKey();
                String queryStr = entry.getValue();
                if(StringUtils.isNotBlank(tableName))
                {
                    if(StringUtils.isNotBlank(queryStr))
                    {
                        dataSet.addTable(tableName, queryStr);
                    }
                    else
                    {
                        dataSet.addTable(tableName);
                    }
                }
            }
        }
        
        writeExcel(dataSet, new FileOutputStream(FILENAME + fileName));
    }
    
    
    /**
     * 导出XML文件,文件名为表名
     * @param connection
     * @param dataSet
     * @param tableMap
     * @throws AmbiguousTableNameException
     * @throws IOException
     * @throws DataSetException
     * @throws FileNotFoundException
     */
    public static void exportXMLFromDataBase(IDatabaseConnection connection, QueryDataSet dataSet,
            Map<String, String> tableMap) throws AmbiguousTableNameException, IOException, DataSetException,
            FileNotFoundException {
        //导出到Excel文件里  
        /*注意这里导入了poi-3.2-FINAL.jar,在这里我用的dbunit-2.4.9.jar
         * 是最新的版本,而poi目前最新的版本是poi-3.10-beta2-20130904.jar,
         * 与dbunit的最新版本一起使用会报错 会出现:
         * java.lang.NoSuchMethodError: org.apache.poi.hssf.usermodel.HSSFCell.setCellValue(Lorg/apache/poi/hssf/usermodel/HSSFRichTextString;)V
         * 而换成poi-3.2-FINAL.jar时则成功导出,生成了两个Sheet,Sheet名为表名
         * 即只能导出一个表中的数据,并且只能导出Excel97-2003*.xls版本的文件
         * 而使用FlatXmlDataSet能够导出多个表中的数据
        */
        if(tableMap != null && !tableMap.isEmpty())
        {
            
            for(Entry<String, String> entry : tableMap.entrySet())
            {
                String tableName = entry.getKey();
                String queryStr = entry.getValue();
                QueryDataSet dataSet1 = new QueryDataSet(connection);
                if(StringUtils.isNotBlank(tableName))
                {
                    if(StringUtils.isNotBlank(queryStr))
                    {
                        dataSet1.addTable(tableName, queryStr);
                        dataSet.addTable(tableName, queryStr);
                    }
                    else
                    {
                        dataSet1.addTable(tableName);
                        dataSet.addTable(tableName);
                    }
                    String fileName = FILENAME + tableName + ".xml";
                    FlatXmlDataSet.write(dataSet1, new FileWriter(fileName), "utf-8");
                }
            }
        }
//            writeExcel(dataSet, new FileOutputStream(FILENAME + "dbTest.xls"));
//             CsvDataSetWriter w = new CsvDataSetWriter(new File(FILENAME+ ".csv"));  
//             w.write(dataSet);  
//             FlatXmlDataSet.write(dataSet, new FileOutputStream(FILENAME));
    }
    
    
    
    
    public static Cell writeDateValue(Workbook book, Sheet sheet, int row,  
            int column, Date value) {  
        Row poiRow = sheet.getRow(row);  
        CreationHelper createHelper = book.getCreationHelper();  
        if (poiRow == null) {  
            poiRow = sheet.createRow(row);  
        }  
        Cell poiCell = poiRow.getCell(column);  
      
        if (poiCell == null) {  
            poiCell = poiRow.createCell(column);  
        }  
      
        CellStyle cellStyle = book.createCellStyle();  
        cellStyle.setDataFormat(createHelper.createDataFormat().getFormat(  
                "yyyy-MM-dd HH:mm:ss"));  
        if (value != null) {  
            poiCell.setCellValue(value);  
        } else {  
            poiCell.setCellValue(new Date());  
        }  
        poiCell.setCellStyle(cellStyle);  
      
        return poiCell;  
    }  
    
    
    public static void writeExcel(IDataSet dataSet, OutputStream out) throws IOException, DataSetException
    {
        HSSFWorkbook workbook = new HSSFWorkbook();
     // 定义3种字体
        HSSFFont normalFont = PoiUtils.createFont(workbook, "宋体", 200,
                (short) (-1), (short) (-1));
        HSSFFont boldFont = PoiUtils.createFont(workbook, "宋体", 180,
                Font.BOLDWEIGHT_BOLD, (short) (-1));
        // 定义基本样式
        HSSFCellStyle objCellStyle = PoiUtils.createCellStyle(workbook, normalFont);
        // 定义样式——有边框
        HSSFCellStyle objBorderCellStyle = PoiUtils.createCellStyle(workbook,objCellStyle, normalFont, CellStyle.ALIGN_CENTER);
        objBorderCellStyle.setBorderBottom(CellStyle.BORDER_THIN);// 下边框
        objBorderCellStyle.setBorderLeft(CellStyle.BORDER_THIN);// 左边框
        objBorderCellStyle.setBorderRight(CellStyle.BORDER_THIN);// 右边框
        objBorderCellStyle.setBorderTop(CellStyle.BORDER_THIN);// 上边框
        HSSFCellStyle objWhiteCellStyle = PoiUtils.createCellStyle(workbook,
                objBorderCellStyle, boldFont, CellStyle.ALIGN_CENTER);
        objWhiteCellStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
        objWhiteCellStyle.setFillForegroundColor(HSSFColor.WHITE.index);
        
        // 题头行高度(大)
        int iTitileRowHeightB = 35;
        //定义样式--日期格式
        HSSFCellStyle objWhiteCellStyleRightDate = PoiUtils.createCellStyle(
                workbook, objBorderCellStyle, normalFont,HSSFCellStyle.ALIGN_RIGHT);
        objWhiteCellStyleRightDate.setDataFormat(workbook.createDataFormat().getFormat("yyyy-MM-dd HH:mm:ss"));
        
        int index = 0;
        for(ITableIterator iterator = dataSet.iterator(); iterator.next();)
        {
            ITable table = iterator.getTable();
            ITableMetaData metaData = table.getTableMetaData();
            Sheet sheet = workbook.createSheet(metaData.getTableName());
            workbook.setSheetName(index, metaData.getTableName());
            Row headerRow = sheet.createRow(0);
            Column columns[] = metaData.getColumns();
            for(int j = 0; j < columns.length; j++)
            {
                Column column = columns[j];
                Cell cell = headerRow.createCell(j);
                cell.setCellValue(new HSSFRichTextString(column.getColumnName()));
            }
    
            for(int j = 0; j < table.getRowCount(); j++)
            {
                HSSFRow row = (HSSFRow) PoiUtils.createRow(sheet, j + 1, iTitileRowHeightB);
                for(int k = 0; k < columns.length; k++)
                {
                    Column column = columns[k];
                    Object value = table.getValue(j, column.getColumnName());
                    if(value == null)
                        continue;
                    if (value instanceof Date)
                    {
                        PoiUtils.cteateCell(row, k, DateUtil.convertToDate(value, "yyyy-MM-dd HH:mm:ss"), objWhiteCellStyleRightDate);
                    }
                    else
                    {
                        PoiUtils.cteateCell(row, k, value, objBorderCellStyle);
                    }
                }
            }
            index++;
        }
    
        workbook.write(out);
        out.flush();
    }


运行后导出excel文件到指定目录。



读取excel文件生成VO

package com.sf.iec.gernaratedata;

import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;

import com.sf.common.util.DateUtil;
import com.sf.iec.common.util.BigDecimalUtils;

/**
 * 从EXCEL数据集文件创建Bean
 */
public class XlsDataSetBeanFactory {

    // 从DbUnit的EXCEL数据集文件创建多个bean
    public static <T> List<T> createBeans(String file, String tableName, Class<T> clazz)
            throws Exception {

        InputStream in = XlsDataSetBeanFactory.class.getResourceAsStream(file);
        XlsWorkBook workbook = new XlsWorkBook(in);
        XlsWorkSheet sheet = workbook.getSheet(tableName);
        List<T> beanList = sheet.buildBeans(clazz);
        
        return beanList;

    }

    public static <T> List<T> createConditionBeans(String file, String tableName, Class<T> clazz, Map<String, Object> conditionMap)
    {
        List<T> beanList = new ArrayList<T>();
        try {
            List<T> list = createBeans(file, tableName, clazz);
            
            if(conditionMap != null && !conditionMap.isEmpty() && list != null && !list.isEmpty())
            {
                Map<Method, Object> methods = new HashMap<Method, Object>();
                
                Map<String, Object> subValueMap = new HashMap<String, Object>();
                Map<String, Object> subQuoteMap = new HashMap<String, Object>();
                for(Entry<String, Object> entry : conditionMap.entrySet())
                {
                    String conditionKey = entry.getKey();
                    if(StringUtils.isNotBlank(conditionKey))
                    {
                        subValueMap.put(entry.getKey().split(",")[0], entry.getValue());
                        if(entry.getKey().split(",").length > 1)
                        {
                            subQuoteMap.put(entry.getKey().split(",")[0], entry.getKey().split(",")[1]);
                        }
                        else
                        {
                            subQuoteMap.put(entry.getKey().split(",")[0], "=");
                        }
                    }
                }
                
                translateCondition(clazz, subValueMap, methods);
                
                for(T objBean : list)
                {
                    int validCount = 0;
                    for(Entry<Method, Object> entry : methods.entrySet())
                    {
                        Object subObj = null;
                        
                        Method fieldMethod = entry.getKey();
                        Object valueObj = entry.getValue();
                        Class<?> subType = fieldMethod.getReturnType();
                        String fieldMethodName = fieldMethod.getName();
                        String methodName = fieldMethodName.substring(3);
                        String compareQuote = "";  //比较符号
                        //对象在MAP中
                        if(subQuoteMap.containsKey(lowerCase(methodName)))
                        {
                            Object objarr = getMemberValue(objBean,fieldMethod);
                            if(objarr != null)
                            {
                                subObj = objarr;
                                compareQuote = (String) subQuoteMap.get(lowerCase(methodName));
                            }
                        }
                        //如果子对象为空或者传入的数据与实际的类型不符合,则不处理
                        if(subObj == null || (valueObj != null && !isSameType(valueObj.getClass(),subType)))
                        {
                            break;
                        }
                        if (subType == BigDecimal.class)
                        {
                            if(StringUtils.isNotBlank(compareQuote))
                            {
                                if(compareQuote.equals("="))
                                {
                                    if(BigDecimalUtils.compareTo((BigDecimal)subObj, (BigDecimal)entry.getValue()) == 0)
                                    {
                                        //如果一致,则计数器加一
                                        validCount++;
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }
                                else if(compareQuote.equals(">"))
                                {   
                                    if(BigDecimalUtils.compareTo((BigDecimal)subObj, (BigDecimal)entry.getValue()) > 0)
                                    {
                                        //如果一致,则计数器加一
                                        validCount++;
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }
                                else if(compareQuote.equals(">="))
                                {   
                                    if(BigDecimalUtils.compareTo((BigDecimal)subObj, (BigDecimal)entry.getValue()) >= 0)
                                    {
                                        //如果一致,则计数器加一
                                        validCount++;
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }
                                else if(compareQuote.equals("<"))
                                {   
                                    if(BigDecimalUtils.compareTo((BigDecimal)subObj, (BigDecimal)entry.getValue()) < 0)
                                    {
                                        //如果一致,则计数器加一
                                        validCount++;
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }
                                else if(compareQuote.equals("<="))
                                {   
                                    if(BigDecimalUtils.compareTo((BigDecimal)subObj, (BigDecimal)entry.getValue()) <= 0)
                                    {
                                        //如果一致,则计数器加一
                                        validCount++;
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }
                            }
                        }
                        else if (subType == Date.class || subType == Timestamp.class)
                        {
                            if(StringUtils.isNotBlank(compareQuote))
                            {
                                if(compareQuote.equals("="))
                                {
                                    if(DateUtil.isSameDay((Date)subObj, (Date)entry.getValue()))
                                    {
                                        //如果一致,则计数器加一
                                        validCount++;
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }
                                else if(compareQuote.equals(">"))
                                {   
                                    if(DateUtil.compareDate((Date)subObj, (Date)entry.getValue(), 0) > 0)
                                    {
                                        //如果一致,则计数器加一
                                        validCount++;
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }
                                else if(compareQuote.equals(">="))
                                {   
                                    if(DateUtil.compareDate((Date)subObj, (Date)entry.getValue(), 0) >= 0)
                                    {
                                        //如果一致,则计数器加一
                                        validCount++;
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }
                                else if(compareQuote.equals("<"))
                                {   
                                    if(DateUtil.compareDate((Date)subObj, (Date)entry.getValue(), 0) < 0)
                                    {
                                        //如果一致,则计数器加一
                                        validCount++;
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }
                                else if(compareQuote.equals("<="))
                                {   
                                    if(DateUtil.compareDate((Date)subObj, (Date)entry.getValue(), 0) <= 0)
                                    {
                                        //如果一致,则计数器加一
                                        validCount++;
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }
                            }
                        }
                        else if (subType == Double.class || subType == double.class)
                        {
                            if(StringUtils.isNotBlank(compareQuote))
                            {
                                if(compareQuote.equals("="))
                                {
                                    if(Double.compare((Double)subObj, (Double)entry.getValue()) == 0)
                                    {
                                        //如果一致,则计数器加一
                                        validCount++;
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }
                                else if(compareQuote.equals(">"))
                                {   
                                    if(Double.compare((Double)subObj, (Double)entry.getValue()) > 0)
                                    {
                                        //如果一致,则计数器加一
                                        validCount++;
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }
                                else if(compareQuote.equals(">="))
                                {   
                                    if(Double.compare((Double)subObj, (Double)entry.getValue()) >= 0)
                                    {
                                        //如果一致,则计数器加一
                                        validCount++;
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }
                                else if(compareQuote.equals("<"))
                                {   
                                    if(Double.compare((Double)subObj, (Double)entry.getValue()) < 0)
                                    {
                                        //如果一致,则计数器加一
                                        validCount++;
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }
                                else if(compareQuote.equals("<="))
                                {   
                                    if(Double.compare((Double)subObj, (Double)entry.getValue()) <= 0)
                                    {
                                        //如果一致,则计数器加一
                                        validCount++;
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }
                            }
                        }
                        else if (subType == Float.class || subType == float.class)
                        {
                            if(StringUtils.isNotBlank(compareQuote))
                            {
                                if(compareQuote.equals("="))
                                {
                                    if(Float.compare((Float)subObj, (Float)entry.getValue()) == 0)
                                    {
                                        //如果一致,则计数器加一
                                        validCount++;
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }
                                else if(compareQuote.equals(">"))
                                {   
                                    if(Float.compare((Float)subObj, (Float)entry.getValue()) > 0)
                                    {
                                        //如果一致,则计数器加一
                                        validCount++;
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }
                                else if(compareQuote.equals(">="))
                                {   
                                    if(Float.compare((Float)subObj, (Float)entry.getValue()) >= 0)
                                    {
                                        //如果一致,则计数器加一
                                        validCount++;
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }
                                else if(compareQuote.equals("<"))
                                {   
                                    if(Float.compare((Float)subObj, (Float)entry.getValue()) < 0)
                                    {
                                        //如果一致,则计数器加一
                                        validCount++;
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }
                                else if(compareQuote.equals("<="))
                                {   
                                    if(Float.compare((Float)subObj, (Float)entry.getValue()) <= 0)
                                    {
                                        //如果一致,则计数器加一
                                        validCount++;
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }
                            }
                        }
                        else if (subType == Long.class || subType == long.class)
                        {
                            if(StringUtils.isNotBlank(compareQuote))
                            {
                                if(compareQuote.equals("="))
                                {
                                    if((Long)subObj == (Long)entry.getValue())
                                    {
                                        //如果一致,则计数器加一
                                        validCount++;
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }
                                else if(compareQuote.equals(">"))
                                {   
                                    if((Long)subObj > (Long)entry.getValue())
                                    {
                                        //如果一致,则计数器加一
                                        validCount++;
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }
                                else if(compareQuote.equals(">="))
                                {   
                                    if((Long)subObj >= (Long)entry.getValue())
                                    {
                                        //如果一致,则计数器加一
                                        validCount++;
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }
                                else if(compareQuote.equals("<"))
                                {   
                                    if((Long)subObj < (Long)entry.getValue())
                                    {
                                        //如果一致,则计数器加一
                                        validCount++;
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }
                                else if(compareQuote.equals("<="))
                                {   
                                    if((Long)subObj <= (Long)entry.getValue())
                                    {
                                        //如果一致,则计数器加一
                                        validCount++;
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }
                            }
                            
                        } else if (subType == Integer.class || subType == int.class)
                        {
                            if(StringUtils.isNotBlank(compareQuote))
                            {
                                if(compareQuote.equals("="))
                                {
                                    if(((Integer)subObj).equals((Integer)entry.getValue()))
                                    {
                                        //如果一致,则计数器加一
                                        validCount++;
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }
                                else if(compareQuote.equals(">"))
                                {   
                                    if((Integer)subObj > (Integer)entry.getValue())
                                    {
                                        //如果一致,则计数器加一
                                        validCount++;
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }
                                else if(compareQuote.equals(">="))
                                {   
                                    if((Integer)subObj >= (Integer)entry.getValue())
                                    {
                                        //如果一致,则计数器加一
                                        validCount++;
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }
                                else if(compareQuote.equals("<"))
                                {   
                                    if((Integer)subObj < (Integer)entry.getValue())
                                    {
                                        //如果一致,则计数器加一
                                        validCount++;
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }
                                else if(compareQuote.equals("<="))
                                {   
                                    if((Integer)subObj <= (Integer)entry.getValue())
                                    {
                                        //如果一致,则计数器加一
                                        validCount++;
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }
                            }
                        }
                        else if(subType == Character.class || subType == char.class)
                        {
                            if(StringUtils.isNotBlank(compareQuote))
                            {
                                if(compareQuote.equals("="))
                                {
                                    if(((Character)subObj).equals((Character)entry.getValue()))
                                    {
                                        //如果一致,则计数器加一
                                        validCount++;
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }
                                else if(compareQuote.equals("<>"))
                                {   
                                    if((Character)subObj != (Character)entry.getValue())
                                    {
                                        //如果一致,则计数器加一
                                        validCount++;
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }
                            }
                        }
                        else if(subType == String.class)
                        {
                            if(StringUtils.isNotBlank(compareQuote))
                            {
                                if(compareQuote.equals("="))
                                {
                                    if(StringUtils.equals((String)subObj, (String)entry.getValue()))
                                    {
                                        //如果一致,则计数器加一
                                        validCount++;
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }
                                else if(compareQuote.equals("<>"))
                                {   
                                    if(!StringUtils.equals((String)subObj, (String)entry.getValue()))
                                    {
                                        //如果一致,则计数器加一
                                        validCount++;
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }
                                else if(compareQuote.equals("like"))
                                {
                                    if(((String)subObj).startsWith((String)entry.getValue()))
                                    {
                                        //如果一致,则计数器加一
                                        validCount++;
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }
                                else if(compareQuote.equals("like%"))
                                {
                                    if(((String)subObj).contains((String)entry.getValue()))
                                    {
                                        //如果一致,则计数器加一
                                        validCount++;
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }
                            }
                        }
                    }
                    if(validCount == methods.size())
                    {
                        beanList.add(objBean);
                        continue;
                    }
                }
            }
            else
            {
                beanList = list;
            }
            
        } catch (Exception e) {
            e.printStackTrace();
        }
        return beanList;
    }
    
    /**
     * 根据传入的字段获取该字段的方法
     * @param clazz
     * @param conditionMap
     * @param methods
     * @return
     */
    public static Map<Method, Object> translateCondition(Class<?> clazz, Map<String, Object> conditionMap,
            Map<Method, Object> methods)
    {
        try {
            
            Object bean = null;
            if(clazz != null)
            {
                bean = clazz.newInstance();
            }
            else
            {
                return methods;
            }
            
            Method[] ms = clazz.getDeclaredMethods();
            
            for(int i=0;i<ms.length;i++){  
                String methodName = ms[i].getName();
                if(methodName.startsWith("get")){
                   if(conditionMap.containsKey(lowerCase(methodName.substring(3)))){  
                       methods.put(ms[i], conditionMap.get(lowerCase(methodName.substring(3))));
                       conditionMap.remove(lowerCase(methodName.substring(3)));
                   }
                   else if(!methodName.equals("equals") && !methodName.equals("hashCode"))
                   {
                       Class<?> subType = (Class<?>) bean.getClass().getDeclaredField(lowerCase(methodName.substring(3))).getType();  
                     //如果子类不属于基础类型,则进入递归
                       if(subType != null && !isBaseClass(subType))
                       {
                           Object subObj = subType.newInstance();
                           Method[] subms = subType.getDeclaredMethods();
                           for(int k=0; k<subms.length; k++)
                           {
                               String subMethodName = subms[k].getName();
                               if(subMethodName.startsWith("get")){
                                  if(conditionMap.containsKey(lowerCase(subMethodName.substring(3)))){  
                                      methods.put(subms[k], conditionMap.get(lowerCase(subMethodName.substring(3))));
                                      conditionMap.remove(lowerCase(subMethodName.substring(3)));
                                  }
                               }
                               else if(!subMethodName.equals("equals") && !subMethodName.equals("hashCode"))
                               {
                                   Class<?> sunType = (Class<?>) subObj.getClass().getDeclaredField(lowerCase(subMethodName.substring(3))).getType();  
                                   //如果子类不属于基础类型,则进入递归
                                     if(sunType != null && !isBaseClass(sunType))
                                     {
                                         Object sunObj = sunType.newInstance();
                                         Method[] sunms = sunType.getDeclaredMethods();
                                         for(int l=0; l<sunms.length; l++)
                                         {
                                             String sunMethodName = sunms[l].getName();
                                             if(sunMethodName.startsWith("get")){
                                                if(conditionMap.containsKey(lowerCase(sunMethodName.substring(3)))){  
                                                    methods.put(sunms[l], conditionMap.get(lowerCase(sunMethodName.substring(3))));
                                                   conditionMap.remove(lowerCase(sunMethodName.substring(3)));
                                                }
                                             }
                                         }
                                     }
                                     else
                                     {
                                       continue;
                                     }
                               }
                           }
                       }
                       else
                       {
                           continue;
                       }
                       /*                       
                       //如果子类不属于基础类型,则进入递归
                       if(subType != null && !isBaseClass(subType))
                       {
                           count++;
                           translateCondition(subType, conditionMap, methods, count);
                           continue;
                       }
                        */                  
                    }
                }
            }
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        return methods;
        
    }
    
    
    /**
     * 获取属性的set方法
     *
     * @param bean
     * @param methodName
     * @return
     */
    public static Method getMethod(Object bean, String setOrGet, String methodName,
            Class<?> clazz) {
        Method method = null;
        String strMethodName = setOrGet + upperCase(methodName);
        try {
            // 通过方法名称获取方法对象
            if("set".equals(setOrGet))
            {
                method = bean.getClass().getMethod(strMethodName, clazz);
            }
            else if("get".equals(setOrGet))
            {
                method = bean.getClass().getMethod(strMethodName);
            }
        } catch (SecurityException e) {
            e.printStackTrace();
            System.out.println("方法[" + methodName + "]映射出出现安全错误");
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
            System.out.println("没有这个方法[" + methodName + "]");
        }
        return method;
    }
    
    /**
     * 将字符串首字母改为大写
     *
     * @param fieldName
     * @return
     */
    public static String upperCase(String fieldName) {
        // 首字母改为大写
        return Character.toUpperCase(fieldName.charAt(0))
                + fieldName.substring(1);
    }
    
    /**
     * 将字符串首字母改为小写
     *
     * @param fieldName
     * @return
     */
    public static String lowerCase(String fieldName) {
        // 首字母改为大写
        return Character.toLowerCase(fieldName.charAt(0))
                + fieldName.substring(1);
    }
    
    /**
     * 判断是否是对象类型(除基础类型以及set等类型外)
     *
     * @param obj
     * @param cls
     * @return
     */
    public static boolean isBaseClass(Class<?> cls) {
        boolean returnFlag = false;
        if (cls == BigDecimal.class) {
            returnFlag = true;
        } else if (cls == BigInteger.class) {
            returnFlag = true;
        } else if (cls == Date.class || cls == Timestamp.class) {
            returnFlag = true;
        } else if (cls == Double.class || cls == double.class) {
            returnFlag = true;
        } else if (cls == Float.class || cls == float.class) {
            returnFlag = true;
        } else if (cls == Long.class || cls == long.class) {
            returnFlag = true;
        } else if (cls == Integer.class || cls == int.class) {
            returnFlag = true;
        }
        else if(cls == Character.class || cls == char.class)
        {
            returnFlag = true;
        }
        else if(cls ==  Set.class || cls == String.class)
        {
            returnFlag = true;
        }
        
        return returnFlag;
    }
    
    /**
     * 获取字段的值
     * @param objBean
     * @param method
     * @return
     */
    public static Object getMemberValue(Object objBean,Method method)    
    {
        Object subObj = null;
        try {
            
            boolean isMember = false;
            try {
                objBean.getClass().getDeclaredMethod(method.getName(), method.getParameterTypes());
                isMember = true;
            } catch (NoSuchMethodException e) {
                isMember = false;
            }
            if(isMember)
            {
                subObj = method.invoke(objBean, new Object[0]);
            }
            else
            {
                Method[] subMethods = objBean.getClass().getDeclaredMethods();
                for(Method subMethod : subMethods)
                {
                    if(!isBaseClass(subMethod.getClass()))
                    {
                        Object sunObject = subMethod.invoke(objBean, new Object[0]);
                        Object sunObj = getMemberValue(sunObject, method);
                        if(sunObj != null)
                        {
                            subObj = sunObj;
                            break;
                        }
                    }
                }
            }
        } catch (SecurityException e) {
        } catch (IllegalArgumentException e) {
        } catch (IllegalAccessException e) {
        } catch (InvocationTargetException e) {
        }
        
        return subObj;
    }
    
    /**
     * 判断是否是相同类型
     * @param frType
     * @param toType
     * @return
     */
    public static boolean isSameType(Class<?> frType, Class<?> toType)
    {
        boolean returnFlag = false;
        if (frType == BigDecimal.class && toType == BigDecimal.class) {
            returnFlag = true;
        } else if (frType == BigInteger.class && toType == BigInteger.class) {
            returnFlag = true;
        } else if ((frType == Date.class || frType == Timestamp.class)
                && (toType == Date.class || toType == Timestamp.class)) {
            returnFlag = true;
        } else if ((frType == Double.class || frType == double.class)
                   && (toType == Double.class || toType == double.class)) {
            returnFlag = true;
        } else if ((frType == Float.class || frType == float.class)
                && (toType == Float.class || toType == float.class)) {
            returnFlag = true;
        } else if ((frType == Long.class || frType == long.class)
                && (toType == Long.class || toType == long.class)) {
            returnFlag = true;
        } else if ((frType == Integer.class || frType == int.class)
                && (toType == Integer.class || toType == int.class)) {
            returnFlag = true;
        }
        else if((frType == Character.class || frType == char.class)
                && (toType == Character.class || toType == char.class))
        {
            returnFlag = true;
        }
        else if((frType ==  Set.class && toType ==  Set.class)
                || (frType == String.class && toType == String.class))
        {
            returnFlag = true;
        }
        
        return returnFlag;
    }
}

POI工具类


import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFPatriarch;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.Region;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.NumberToTextConverter;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;

@SuppressWarnings("deprecation")
public final class PoiUtils {

    private PoiUtils() {

    }

    /**
     * 创建字体
     *
     * @param workbook
     * @param fontName
     * @param fontHeight
     * @param boldWeight
     * @param color
     * @return 字体对象
     */
    public static HSSFFont createFont(HSSFWorkbook workbook, String fontName,
            int fontHeight, short boldWeight, short color) {
        HSSFFont fontStyle = workbook.createFont();
        fontStyle.setFontHeight((short) fontHeight);
        fontStyle.setFontName(fontName);
        if (boldWeight > 0) {
            fontStyle.setBoldweight(boldWeight);
        }
        if (color > 0) {
            fontStyle.setColor(color);
        }
        return fontStyle;
    }

    /**
     * 创建单元格样式
     *
     * @param workbook
     *            excel对象
     * @param font
     *            字体
     * @return 单元格样式
     */
    public static HSSFCellStyle createCellStyle(HSSFWorkbook workbook,
            HSSFFont font) {
        HSSFCellStyle objCellStyle = workbook.createCellStyle();
        objCellStyle.setFont(font);
        objCellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        objCellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        objCellStyle.setWrapText(true);
        return objCellStyle;
    }

    /**
     * 创建单元格样式,可以从另一样式中继承设置
     *
     * @param workbook
     *            excel对象
     * @param cellStyle
     *            另一样式
     * @param font
     *            字体
     * @param alignment
     *            对齐
     * @return 新样式
     */
    public static HSSFCellStyle createCellStyle(HSSFWorkbook workbook,
            HSSFCellStyle cellStyle, HSSFFont font, short alignment) {
        HSSFCellStyle objNewCellStyle = workbook.createCellStyle();
        objNewCellStyle.setFont(font == null ? workbook.getFontAt(cellStyle
                .getFontIndex()) : font);
        objNewCellStyle.setAlignment(alignment < 0 ? cellStyle.getAlignment()
                : alignment);
        objNewCellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        objNewCellStyle.setWrapText(true);
        objNewCellStyle.setBorderBottom(cellStyle.getBorderBottom());// 下边框
        objNewCellStyle.setBorderLeft(cellStyle.getBorderLeft());// 左边框
        objNewCellStyle.setBorderRight(cellStyle.getBorderRight());// 右边框
        objNewCellStyle.setBorderTop(cellStyle.getBorderTop());// 上边框
        return objNewCellStyle;
    }

    /**
     * 创建行
     *
     * @param sheet
     *            所在工作簿
     * @param rowId
     *            行号
     * @param height
     *            行高
     * @return 行对象
     */
    public static HSSFRow createRow(HSSFSheet sheet, int rowId, int height) {
        HSSFRow objRow = sheet.createRow(rowId);
        objRow.setHeightInPoints(height);
        return objRow;
    }

    /**
     * 创建文本类型的单元格
     *
     * @param row
     *            行对象
     * @param colFrom
     *            单元格开始列号
     * @param value
     *            单元格的值
     * @param cellStyle
     *            单元格的样式
     */
    public static void createStringCell(HSSFRow row, int colFrom, String value,
            HSSFCellStyle cellStyle) {
        HSSFCell objCell = row.createCell(colFrom);
        objCell.setCellValue(new HSSFRichTextString(value));
        objCell.setCellStyle(cellStyle);
        objCell.setCellType(HSSFCell.ENCODING_UTF_16);
    }

    /**
     * 创建文本类型的单元格
     *
     * @param row
     *            行对象
     * @param colFrom
     *            单元格开始列号
     * @param value
     *            单元格的值
     * @param cellStyle
     *            单元格的样式
     * @param strFormula
     *            参数
     */
    public static void createStringCell(HSSFRow row, int colFrom, String value,
            HSSFCellStyle cellStyle, String strFormula) {
        HSSFCell objCell = row.createCell(colFrom);
        objCell.setCellValue(new HSSFRichTextString(value));
        objCell.setCellStyle(cellStyle);
        objCell.setCellType(HSSFCell.ENCODING_UTF_16);
        if (StringUtil.isNotBlank(strFormula)) {
            objCell.setCellFormula(strFormula);
        }
    }

    /**
     * 合并单元格
     *
     * @param sheet
     *            所在工作簿
     * @param cellStyle
     *            合并后单元格的样式
     * @param rowFrom
     *            开始行号
     * @param colFrom
     *            开始列号
     * @param rowTo
     *            结束行号
     * @param colTo
     *            结束列号
     */
    public static void mergeCells(HSSFSheet sheet, HSSFCellStyle cellStyle,
            int rowFrom, int colFrom, int rowTo, int colTo) {
        HSSFRow objRow = null;
        HSSFCell objCell = null;
        for (int i = rowFrom; i <= rowTo; i++) {
            objRow = sheet.getRow(i);
            if (objRow == null) {
                objRow = sheet.createRow(i);
            }
            for (int j = colFrom; j <= colTo; j++) {
                // 为被合并的单元格创建单元格并设置格式(主要是为了设置合并单元格的线条,如果不创建则合并单元格的线条会出现问题)
                objCell = objRow.getCell(j);
                if (objCell == null) {
                    objCell = objRow.createCell(j);
                    objCell.setCellValue(new HSSFRichTextString(""));
                    objCell.setCellStyle(cellStyle);
                }
            }
        }
        Region objRegion = new Region(rowFrom, (short) colFrom, rowTo,
                (short) colTo);
        sheet.addMergedRegion(objRegion);
    }

    /**
     * 画斜线
     *
     * @param patriarch
     *            所在工作簿
     * @param rowFrom
     *            起点所在行
     * @param colFrom
     *            起点所在列
     * @param rowTo
     *            终点所在行
     * @param colTo
     *            终点所在列
     */
    public static void drawLine(HSSFPatriarch patriarch, int rowFrom,
            int colFrom, int rowTo, int colTo) {
        HSSFClientAnchor anchor = new HSSFClientAnchor();
        anchor.setAnchor((short) colFrom, rowFrom, 0, 0, (short) colTo, rowTo,
                0, 0);
        patriarch.createSimpleShape(anchor);
    }

    /**
     * 创建文本类型的单元格
     *
     * @param row
     *            行对象
     * @param colFrom
     *            单元格开始列号
     * @param value
     *            单元格的值
     * @param cellStyle
     *            单元格的样式
     * @param objWb
     *            当前工作薄对象
     */
    public static void createTextStringCell(HSSFRow row, int colFrom,
            String value, HSSFCellStyle cellStyle, HSSFWorkbook objWb) {
        HSSFCell cell = row.createCell(colFrom);
        if (cell.getCellType() != 1) {
            cell.setCellType(HSSFCell.CELL_TYPE_STRING);
        }
        HSSFDataFormat format = objWb.createDataFormat();
        cellStyle.setDataFormat(format.getFormat("@"));
        cell.setCellStyle(cellStyle);
        cell.setCellValue(new HSSFRichTextString(value));
    }

    /**
     * 创建内容单元格
     *
     * @param row
     *            HSSFRow
     * @param colFrom
     *            short型的列索引
     * @param value
     *            对齐方式
     * @param cellStyle
     *            列值
     */
    @SuppressWarnings("boxing")
    public static void cteateCell(HSSFRow row, int colFrom, Object value,
            HSSFCellStyle cellStyle) {
        HSSFCell objCell = row.createCell(colFrom);
        if (value instanceof Double) {
            objCell.setCellValue(Double.parseDouble(StringUtil.valueOf(value)));
        } else if (value instanceof Date) {
            objCell.setCellValue((Date) value);
        } else if (value instanceof Boolean) {
            objCell.setCellValue((Boolean) value);
        } else if (value instanceof Calendar) {
            objCell.setCellValue((Calendar) value);
        } else {
            objCell.setCellValue(new HSSFRichTextString(StringUtil
                    .valueOf(value)));
        }
        objCell.setCellStyle(cellStyle);
    }

    /**
     * 创建内容单元格
     *
     * @param row
     *            HSSFRow
     * @param colFrom
     *            short型的列索引
     * @param value
     *            对齐方式
     * @param cellStyle
     *            列值
     * @param strFormula
     *            计算公式
     */
    @SuppressWarnings("boxing")
    public static void cteateCell(HSSFRow row, int colFrom, Object value,
            HSSFCellStyle cellStyle, String strFormula) {
        HSSFCell objCell = row.createCell(colFrom);
        if (value instanceof Double) {
            objCell.setCellValue(Double.parseDouble(StringUtil.valueOf(value)));
        } else if (value instanceof Date) {
            objCell.setCellValue((Date) value);
        } else if (value instanceof Boolean) {
            objCell.setCellValue((Boolean) value);
        } else if (value instanceof Calendar) {
            objCell.setCellValue((Calendar) value);
        } else {
            objCell.setCellValue(new HSSFRichTextString(StringUtil
                    .valueOf(value)));
        }
        objCell.setCellStyle(cellStyle);
        objCell.setCellType(HSSFCell.ENCODING_UTF_16);
        if (StringUtil.isNotBlank(strFormula)) {
            objCell.setCellFormula(strFormula);
        }
    }

    /**
     * 创建内容单元格
     *
     * @param row
     *            HSSFRow
     * @param colFrom
     *            short型的列索引
     * @param value
     *            对齐方式
     * @param cellStyle
     *            列值
     */
    @SuppressWarnings("boxing")
    public static void createCell(HSSFRow row, int colFrom, Object value,
            HSSFCellStyle cellStyle) {
        HSSFCell objCell = row.createCell(colFrom);
        if (value instanceof Double) {
            objCell.setCellValue(Double.parseDouble(StringUtil.valueOf(value)));
        } else if (value instanceof Date) {
            objCell.setCellValue((Date) value);
        } else if (value instanceof Boolean) {
            objCell.setCellValue((Boolean) value);
        } else if (value instanceof Calendar) {
            objCell.setCellValue((Calendar) value);
        } else {
            objCell.setCellValue(new HSSFRichTextString(StringUtil
                    .valueOf(value)));
        }
        objCell.setCellStyle(cellStyle);
    }

    /**
     * 创建数值类型的单元格
     *
     * @param row
     *            行对象
     * @param colFrom
     *            单元格开始列号
     * @param value
     *            单元格的值
     * @param cellStyle
     *            单元格的样式
     */
    public static void createNumericCell(HSSFRow row, int colFrom,
            double value, HSSFCellStyle cellStyle) {
        HSSFCell objCell = row.createCell(colFrom);
        objCell.setCellValue(value);
        objCell.setCellStyle(cellStyle);
        objCell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
    }
    
    
    /**
     * 创建字体 SXSSFWorkbook 大数据量EXCEL文件
     *
     * @param workbook
     * @param fontName
     * @param fontHeight
     * @param boldWeight
     * @param color
     * @return 字体对象
     */
    public static Font createFont(Workbook workbook, String fontName,
            int fontHeight, short boldWeight, short color) {
        Font fontStyle = workbook.createFont();
        fontStyle.setFontHeight((short) fontHeight);
        fontStyle.setFontName(fontName);
        if (boldWeight > 0) {
            fontStyle.setBoldweight(boldWeight);
        }
        if (color > 0) {
            fontStyle.setColor(color);
        }
        return fontStyle;
    }
    
    
    /**
     * 创建单元格样式 大数据量EXCEL文件
     *
     * @param workbook
     *            excel对象
     * @param font
     *            字体
     * @return 单元格样式
     */
    public static CellStyle createCellStyle(Workbook workbook,
            Font font) {
        CellStyle objCellStyle = workbook.createCellStyle();
        objCellStyle.setFont(font);
        objCellStyle.setAlignment(CellStyle.ALIGN_CENTER);
        objCellStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
        objCellStyle.setWrapText(true);
        return objCellStyle;
    }
    
    /**
     * 创建单元格样式,可以从另一样式中继承设置  大数据量EXCEL文件
     *
     * @param workbook
     *            excel对象
     * @param cellStyle
     *            另一样式
     * @param font
     *            字体
     * @param alignment
     *            对齐
     * @return 新样式
     */
    public static CellStyle createCellStyle(Workbook workbook,
            CellStyle cellStyle, Font font, short alignment) {
        CellStyle objNewCellStyle = workbook.createCellStyle();
        objNewCellStyle.setFont(font == null ? workbook.getFontAt(cellStyle
                .getFontIndex()) : font);
        objNewCellStyle.setAlignment(alignment < 0 ? cellStyle.getAlignment()
                : alignment);
        objNewCellStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
        objNewCellStyle.setWrapText(true);
        objNewCellStyle.setBorderBottom(cellStyle.getBorderBottom());// 下边框
        objNewCellStyle.setBorderLeft(cellStyle.getBorderLeft());// 左边框
        objNewCellStyle.setBorderRight(cellStyle.getBorderRight());// 右边框
        objNewCellStyle.setBorderTop(cellStyle.getBorderTop());// 上边框
        return objNewCellStyle;
    }
    
    /**
     * 创建行 大数据量EXCEL文件
     *
     * @param sheet
     *            所在工作簿
     * @param rowId
     *            行号
     * @param height
     *            行高
     * @return 行对象
     */
    public static Row createRow(Sheet sheet, int rowId, int height) {
        Row objRow = sheet.createRow(rowId);
        objRow.setHeightInPoints(height);
        return objRow;
    }
    
    /**
     * 创建内容单元格 大数据量EXCEL文件
     *
     * @param row
     *            Row
     * @param colFrom
     *            short型的列索引
     * @param value
     *            对齐方式
     * @param cellStyle
     *            列值
     */
    @SuppressWarnings("boxing")
    public static void cteateCell(Row row, int colFrom, Object value,
            CellStyle cellStyle) {
        Cell objCell = row.createCell(colFrom);
        if (value instanceof Double) {
            objCell.setCellValue(Double.parseDouble(StringUtil.valueOf(value)));
        } else if (value instanceof Date) {
            objCell.setCellValue((Date) value);
        } else if (value instanceof Boolean) {
            objCell.setCellValue((Boolean) value);
        } else if (value instanceof Calendar) {
            objCell.setCellValue((Calendar) value);
        } else {
            objCell.setCellValue(new XSSFRichTextString(StringUtil
                    .valueOf(value)));
        }
        objCell.setCellStyle(cellStyle);
    }

    
    /**
     * 合并单元格 大数据量EXCEL文件
     *
     * @param sheet
     *            所在工作簿
     * @param cellStyle
     *            合并后单元格的样式
     * @param rowFrom
     *            开始行号
     * @param colFrom
     *            开始列号
     * @param rowTo
     *            结束行号
     * @param colTo
     *            结束列号
     */
    public static void mergeCells(Sheet sheet, CellStyle cellStyle,
            int rowFrom, int colFrom, int rowTo, int colTo) {
        Row objRow = null;
        Cell objCell = null;
        for (int i = rowFrom; i <= rowTo; i++) {
            objRow = sheet.getRow(i);
            if (objRow == null) {
                objRow = sheet.createRow(i);
            }
            for (int j = colFrom; j <= colTo; j++) {
                // 为被合并的单元格创建单元格并设置格式(主要是为了设置合并单元格的线条,如果不创建则合并单元格的线条会出现问题)
                objCell = objRow.getCell(j);
                if (objCell == null) {
                    objCell = objRow.createCell(j);
                    objCell.setCellValue(new XSSFRichTextString(""));
                    objCell.setCellStyle(cellStyle);
                }
            }
        }
        CellRangeAddress objRegion = new CellRangeAddress(rowFrom,  rowTo, (short) colFrom,
                (short) colTo);
        sheet.addMergedRegion(objRegion);
    }
    
    /**
     *  POI在读取值的时候会因为类型的不同读取的值不同,而且如果读取不同类型的值会报出异常,所以在这里统一处理
     *  读取Cell的内容值
     *  1.String直接读取
     *  2.整数类型消除小数点
     *  3.浮点类型直接读取
     *  4.公式类型计算公式值
     *  5.错误类型和BLANK类型返回Null
     *  
     *  PS:这里对于一些Excel特别日期格式无法读取,比如包含中文的
     */
    public final static String DATE_OUTPUT_PATTERNS = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";  
    public static String getCellContent(Cell cell) {
        if(cell==null)
            return null;
        String ret;  
        switch (cell.getCellType()) {  
        case Cell.CELL_TYPE_BLANK:  
            ret = "";  
            break;  
        case Cell.CELL_TYPE_BOOLEAN:  
            ret = String.valueOf(cell.getBooleanCellValue());  
            break;  
        case Cell.CELL_TYPE_ERROR:  
            ret = null;  
            break;  
        case Cell.CELL_TYPE_FORMULA:  
            Workbook wb = cell.getSheet().getWorkbook();  
            CreationHelper crateHelper = wb.getCreationHelper();  
            FormulaEvaluator evaluator = crateHelper.createFormulaEvaluator();  
            ret = getCellContent(evaluator.evaluateInCell(cell));  
            break;
        case Cell.CELL_TYPE_NUMERIC:
            //这里对于一些Excel特别日期格式无法读取,比如包含中文的
            if (org.apache.poi.ss.usermodel.DateUtil.isCellDateFormatted(cell)) {
                String strFormatStyle = cell.getCellStyle().getDataFormatString();
                SimpleDateFormat objSimpleDateFormat = new SimpleDateFormat(strFormatStyle);
                return objSimpleDateFormat.format(cell.getDateCellValue());
            } else {
                ret = NumberToTextConverter.toText(cell.getNumericCellValue());  
            }  
            break;  
        case Cell.CELL_TYPE_STRING:  
            ret = cell.getRichStringCellValue().getString();  
            break;  
        default:  
            ret = null;  
        }  
          
        return ret; //有必要自行trim  
    }  
}





0 1
原创粉丝点击