java Excel导出以及读取Excel数据

本文介绍如何使用Java和Apache POI库进行Excel文件的导出和读取操作,包括Maven依赖配置、导出Excel的具体实现、读取Excel数据的方法及其实现细节。

                                             java  Excel导出

       工具:eclipse

       框架:maven+springboot

1:pom.xml添加jar包

          <dependency>                                                      
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.15</version>
        </dependency>

          <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.15</version>
        </dependency>

     2:新建util类ExcelUtil  

          

package com.ccic.gzh.console.common.util;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

public class ExcelUtil {
    /**
     * 导出Excel
     * @param sheetName sheet名称
     * @param title 标题
     * @param values 内容
     * @param wb HSSFWorkbook对象
     * @return
     */
    public static HSSFWorkbook getHSSFWorkbook(String sheetName,String []title,String [][]values, HSSFWorkbook wb){

        // 第一步,创建一个HSSFWorkbook,对应一个Excel文件
        if(wb == null){
            wb = new HSSFWorkbook();
        }

        // 第二步,在workbook中添加一个sheet,对应Excel文件中的sheet
        HSSFSheet sheet = wb.createSheet(sheetName);

        // 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制
        HSSFRow row = sheet.createRow(0);

        // 第四步,创建单元格,并设置值表头 设置表头居中
        HSSFCellStyle style = wb.createCellStyle();
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式

        //声明列对象
        HSSFCell cell = null;

        //创建标题
        for(int i=0;i<title.length;i++){
            cell = row.createCell(i);
            cell.setCellValue(title[i]);
            cell.setCellStyle(style);
        }

        //创建内容
        for(int i=0;i<values.length;i++){
            row = sheet.createRow(i + 1);
            for(int j=0;j<values[i].length;j++){
                //将内容按顺序赋给对应的列对象
                row.createCell(j).setCellValue(values[i][j]);
            }
        }
        return wb;
    }
}


3:新建实体类TpolicyNauto

package com.ccic.gzh.console.domain;

import java.math.BigDecimal;
import java.util.Date;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

/**
 *
 * This class was generated by MyBatis Generator.
 * This class corresponds to the database table T_POLICY_NAUTO
 *
 * @mbg.generated do_not_delete_during_merge
 */

public class TpolicyNauto{
    /**
     *
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column T_POLICY_NAUTO.ID
     *
     * @mbg.generated
     */
    //private Long id;

    /**
     *
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column T_POLICY_NAUTO.REQ_TIME
     *
     * @mbg.generated
     */
    private String reqTime;

    /**
     *
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column T_POLICY_NAUTO.REQ_NO
     *
     * @mbg.generated
     */
    private String reqNo;

    /**
     *
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column T_POLICY_NAUTO.SYS_CODE
     *
     * @mbg.generated
     */
    private String sysCode;

    /**
     *
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column T_POLICY_NAUTO.TRANSACTION_NO
     *
     * @mbg.generated
     */
    private String transactionNo;

    /**
     *
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column T_POLICY_NAUTO.POLICY_NO
     *
     * @mbg.generated
     */
    private String policyNo;

    /**
     *
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column T_POLICY_NAUTO.PROPOSAL_NO
     *
     * @mbg.generated
     */
    private String proposalNo;

    /**
     *
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column T_POLICY_NAUTO.COMBIN_POLICY
     *
     * @mbg.generated
     */
    private String combinPolicy;

    /**
     *
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column T_POLICY_NAUTO.COM_CODE
     *
     * @mbg.generated
     */
    private String comCode;

    /**
     *
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column T_POLICY_NAUTO.COLLECTION_DATE
     *
     * @mbg.generated
     */
    private String collectionDate;

    /**
     *
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column T_POLICY_NAUTO.CLASS_CODE
     *
     * @mbg.generated
     */
    private String classCode;

    /**
     *
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column T_POLICY_NAUTO.CLASS_NAME
     *
     * @mbg.generated
     */
    private String className;

    /**
     *
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column T_POLICY_NAUTO.PREMIUM_FEE
     *
     * @mbg.generated
     */
    private BigDecimal premiumFee;

    /**
     *
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column T_POLICY_NAUTO.COMMISION_RATE
     *
     * @mbg.generated
     */
    private BigDecimal commisionRate;

    /**
     *
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column T_POLICY_NAUTO.COMMISION_FEE
     *
     * @mbg.generated
     */
    private BigDecimal commisionFee;

    /**
     *
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column T_POLICY_NAUTO.KIND_RATE
     *
     * @mbg.generated
     */
    private BigDecimal kindRate;

    /**
     *
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column T_POLICY_NAUTO.CREATE_TIME
     *
     * @mbg.generated
     */
    private Date createTime;

    /**
     *
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column T_POLICY_NAUTO.UPDATE_TIME
     *
     * @mbg.generated
     */
    private Date updateTime;

    /**
     * This method was generated by MyBatis Generator.
     * This method returns the value of the database column T_POLICY_NAUTO.ID
     *
     * @return the value of T_POLICY_NAUTO.ID
     *
     * @mbg.generated
     */
   /* public Long getId() {
        return id;
    }*/

    /**
     * This method was generated by MyBatis Generator.
     * This method sets the value of the database column T_POLICY_NAUTO.ID
     *
     * @param id the value for T_POLICY_NAUTO.ID
     *
     * @mbg.generated
     */
   /* public void setId(Long id) {
        this.id = id;
    }*/

    /**
     * This method was generated by MyBatis Generator.
     * This method returns the value of the database column T_POLICY_NAUTO.REQ_TIME
     *
     * @return the value of T_POLICY_NAUTO.REQ_TIME
     *
     * @mbg.generated
     */
    public String getReqTime() {
        return reqTime;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method sets the value of the database column T_POLICY_NAUTO.REQ_TIME
     *
     * @param reqTime the value for T_POLICY_NAUTO.REQ_TIME
     *
     * @mbg.generated
     */
    public void setReqTime(String reqTime) {
        this.reqTime = reqTime;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method returns the value of the database column T_POLICY_NAUTO.REQ_NO
     *
     * @return the value of T_POLICY_NAUTO.REQ_NO
     *
     * @mbg.generated
     */
    public String getReqNo() {
        return reqNo;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method sets the value of the database column T_POLICY_NAUTO.REQ_NO
     *
     * @param reqNo the value for T_POLICY_NAUTO.REQ_NO
     *
     * @mbg.generated
     */
    public void setReqNo(String reqNo) {
        this.reqNo = reqNo;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method returns the value of the database column T_POLICY_NAUTO.SYS_CODE
     *
     * @return the value of T_POLICY_NAUTO.SYS_CODE
     *
     * @mbg.generated
     */
    public String getSysCode() {
        return sysCode;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method sets the value of the database column T_POLICY_NAUTO.SYS_CODE
     *
     * @param sysCode the value for T_POLICY_NAUTO.SYS_CODE
     *
     * @mbg.generated
     */
    public void setSysCode(String sysCode) {
        this.sysCode = sysCode;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method returns the value of the database column T_POLICY_NAUTO.TRANSACTION_NO
     *
     * @return the value of T_POLICY_NAUTO.TRANSACTION_NO
     *
     * @mbg.generated
     */
    public String getTransactionNo() {
        return transactionNo;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method sets the value of the database column T_POLICY_NAUTO.TRANSACTION_NO
     *
     * @param transactionNo the value for T_POLICY_NAUTO.TRANSACTION_NO
     *
     * @mbg.generated
     */
    public void setTransactionNo(String transactionNo) {
        this.transactionNo = transactionNo;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method returns the value of the database column T_POLICY_NAUTO.POLICY_NO
     *
     * @return the value of T_POLICY_NAUTO.POLICY_NO
     *
     * @mbg.generated
     */
    public String getPolicyNo() {
        return policyNo;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method sets the value of the database column T_POLICY_NAUTO.POLICY_NO
     *
     * @param policyNo the value for T_POLICY_NAUTO.POLICY_NO
     *
     * @mbg.generated
     */
    public void setPolicyNo(String policyNo) {
        this.policyNo = policyNo;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method returns the value of the database column T_POLICY_NAUTO.PROPOSAL_NO
     *
     * @return the value of T_POLICY_NAUTO.PROPOSAL_NO
     *
     * @mbg.generated
     */
    public String getProposalNo() {
        return proposalNo;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method sets the value of the database column T_POLICY_NAUTO.PROPOSAL_NO
     *
     * @param proposalNo the value for T_POLICY_NAUTO.PROPOSAL_NO
     *
     * @mbg.generated
     */
    public void setProposalNo(String proposalNo) {
        this.proposalNo = proposalNo;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method returns the value of the database column T_POLICY_NAUTO.COMBIN_POLICY
     *
     * @return the value of T_POLICY_NAUTO.COMBIN_POLICY
     *
     * @mbg.generated
     */
    public String getCombinPolicy() {
        return combinPolicy;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method sets the value of the database column T_POLICY_NAUTO.COMBIN_POLICY
     *
     * @param combinPolicy the value for T_POLICY_NAUTO.COMBIN_POLICY
     *
     * @mbg.generated
     */
    public void setCombinPolicy(String combinPolicy) {
        this.combinPolicy = combinPolicy;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method returns the value of the database column T_POLICY_NAUTO.COM_CODE
     *
     * @return the value of T_POLICY_NAUTO.COM_CODE
     *
     * @mbg.generated
     */
    public String getComCode() {
        return comCode;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method sets the value of the database column T_POLICY_NAUTO.COM_CODE
     *
     * @param comCode the value for T_POLICY_NAUTO.COM_CODE
     *
     * @mbg.generated
     */
    public void setComCode(String comCode) {
        this.comCode = comCode;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method returns the value of the database column T_POLICY_NAUTO.COLLECTION_DATE
     *
     * @return the value of T_POLICY_NAUTO.COLLECTION_DATE
     *
     * @mbg.generated
     */
    public String getCollectionDate() {
        return collectionDate;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method sets the value of the database column T_POLICY_NAUTO.COLLECTION_DATE
     *
     * @param collectionDate the value for T_POLICY_NAUTO.COLLECTION_DATE
     *
     * @mbg.generated
     */
    public void setCollectionDate(String collectionDate) {
        this.collectionDate = collectionDate;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method returns the value of the database column T_POLICY_NAUTO.CLASS_CODE
     *
     * @return the value of T_POLICY_NAUTO.CLASS_CODE
     *
     * @mbg.generated
     */
    public String getClassCode() {
        return classCode;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method sets the value of the database column T_POLICY_NAUTO.CLASS_CODE
     *
     * @param classCode the value for T_POLICY_NAUTO.CLASS_CODE
     *
     * @mbg.generated
     */
    public void setClassCode(String classCode) {
        this.classCode = classCode;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method returns the value of the database column T_POLICY_NAUTO.CLASS_NAME
     *
     * @return the value of T_POLICY_NAUTO.CLASS_NAME
     *
     * @mbg.generated
     */
    public String getClassName() {
        return className;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method sets the value of the database column T_POLICY_NAUTO.CLASS_NAME
     *
     * @param className the value for T_POLICY_NAUTO.CLASS_NAME
     *
     * @mbg.generated
     */
    public void setClassName(String className) {
        this.className = className;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method returns the value of the database column T_POLICY_NAUTO.PREMIUM_FEE
     *
     * @return the value of T_POLICY_NAUTO.PREMIUM_FEE
     *
     * @mbg.generated
     */
    public BigDecimal getPremiumFee() {
        return premiumFee;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method sets the value of the database column T_POLICY_NAUTO.PREMIUM_FEE
     *
     * @param premiumFee the value for T_POLICY_NAUTO.PREMIUM_FEE
     *
     * @mbg.generated
     */
    public void setPremiumFee(BigDecimal premiumFee) {
        this.premiumFee = premiumFee;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method returns the value of the database column T_POLICY_NAUTO.COMMISION_RATE
     *
     * @return the value of T_POLICY_NAUTO.COMMISION_RATE
     *
     * @mbg.generated
     */
    public BigDecimal getCommisionRate() {
        return commisionRate;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method sets the value of the database column T_POLICY_NAUTO.COMMISION_RATE
     *
     * @param commisionRate the value for T_POLICY_NAUTO.COMMISION_RATE
     *
     * @mbg.generated
     */
    public void setCommisionRate(BigDecimal commisionRate) {
        this.commisionRate = commisionRate;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method returns the value of the database column T_POLICY_NAUTO.COMMISION_FEE
     *
     * @return the value of T_POLICY_NAUTO.COMMISION_FEE
     *
     * @mbg.generated
     */
    public BigDecimal getCommisionFee() {
        return commisionFee;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method sets the value of the database column T_POLICY_NAUTO.COMMISION_FEE
     *
     * @param commisionFee the value for T_POLICY_NAUTO.COMMISION_FEE
     *
     * @mbg.generated
     */
    public void setCommisionFee(BigDecimal commisionFee) {
        this.commisionFee = commisionFee;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method returns the value of the database column T_POLICY_NAUTO.KIND_RATE
     *
     * @return the value of T_POLICY_NAUTO.KIND_RATE
     *
     * @mbg.generated
     */
    public BigDecimal getKindRate() {
        return kindRate;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method sets the value of the database column T_POLICY_NAUTO.KIND_RATE
     *
     * @param kindRate the value for T_POLICY_NAUTO.KIND_RATE
     *
     * @mbg.generated
     */
    public void setKindRate(BigDecimal kindRate) {
        this.kindRate = kindRate;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method returns the value of the database column T_POLICY_NAUTO.CREATE_TIME
     *
     * @return the value of T_POLICY_NAUTO.CREATE_TIME
     *
     * @mbg.generated
     */
    public Date getCreateTime() {
        return createTime;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method sets the value of the database column T_POLICY_NAUTO.CREATE_TIME
     *
     * @param createTime the value for T_POLICY_NAUTO.CREATE_TIME
     *
     * @mbg.generated
     */
    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method returns the value of the database column T_POLICY_NAUTO.UPDATE_TIME
     *
     * @return the value of T_POLICY_NAUTO.UPDATE_TIME
     *
     * @mbg.generated
     */
    public Date getUpdateTime() {
        return updateTime;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method sets the value of the database column T_POLICY_NAUTO.UPDATE_TIME
     *
     * @param updateTime the value for T_POLICY_NAUTO.UPDATE_TIME
     *
     * @mbg.generated
     */
    public void setUpdateTime(Date updateTime) {
        this.updateTime = updateTime;
    }
    
    private String isnewCar;

    public String getIsnewCar() {
        return isnewCar;
    }

    public void setIsnewCar(String isnewCar) {
        this.isnewCar = isnewCar;
    }


}

 

 

4:Controller类

 

 /**
     * 非车险保单
     * @param tpolicyNauto
     * @param request
     * @param response
     */
    @RequestMapping(value = "/tpolicyNautoByreqTime", method = { RequestMethod.GET, RequestMethod.POST })
    public void tpolicyAutoByreqTime(HttpServletRequest request,
            HttpServletResponse response) {
        
        ClientResponse res = ClientResponse.ok();
        TimeQueryVo tpolicyNauto = new TimeQueryVo();
        tpolicyNauto.setStartTime(request.getParameter("startTime"));
        tpolicyNauto.setEndTime(request.getParameter("endTime"));
        System.out.println(request.getParameter("startTime")+","+request.getParameter("endTime"));
        //tpolicyNauto.setReqTime(DateUtils.getlastDay());
        // 获取数据
        List<TpolicyNauto> list = tpolicyNautoService.exportTpolicyAutoByreqTime(tpolicyNauto);
        
        // excel标题
        String[] title = { "请求时间", "请求流水号", "交易流水号", "保单号", "实收付日期", "机构代码", "联合销售标志", 
                "险类代码", "险类名称", "新/转续标志","不含税保费","产品佣金比例", "跟单佣金比例", "跟单费用" };

        // excel文件名
        String fileName =  "非车险保单.xls";

        // sheet名
        String sheetName = "非车险保单";
         String[][] content=new String[list.size()][title.length];
        for (int i = 0; i < list.size(); i++) {
            
            //content[i] = new String[title.length];
            TpolicyNauto obj = list.get(i);
            content[i][0] = obj.getReqTime();
            content[i][1] = obj.getReqNo();
            content[i][2] = obj.getTransactionNo();
            content[i][3] = obj.getPolicyNo();
            content[i][4] = obj.getCollectionDate();
            content[i][5] = obj.getComCode();
            content[i][6] = obj.getCombinPolicy();
            content[i][7] = obj.getClassCode();
            content[i][8] = obj.getClassName();
            content[i][9] = obj.getIsnewCar();
            content[i][10] = obj.getPremiumFee().toString();
            content[i][11] = obj.getKindRate().toString();
            content[i][12] = obj.getCommisionRate().toString();
            content[i][13] = obj.getCommisionFee().toString();
        }

        // 创建HSSFWorkbook
        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null);
        
        // 响应到客户端
        res.setData(wb);
        try {
            this.setResponseHeader(response, fileName);
            OutputStream os = response.getOutputStream();
            
            wb.write(os);
            os.flush();
            os.close();
            
        } catch (Exception e) {
            e.printStackTrace();
        }
        //return res;
    }
// 发送响应流方法
    public void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(), "utf-8");
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            response.setContentType("application/octet-stream;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("gb2312"),"iso8859-1"));
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

 

 

 

                             java 读取Excel数据

 

 

1:util类

package com.utils;

import com.common.Common;

public class Util {
    /**
          * get postfix of the path
         * @param path
          * @return
          */
         public static String getPostfix(String path) {
             if (path == null || Common.EMPTY.equals(path.trim())) {
                return Common.EMPTY;
             }
             if (path.contains(Common.POINT)) {
                 return path.substring(path.lastIndexOf(Common.POINT) + 1, path.length());
             }
             return Common.EMPTY;
         }
}

 


2:common类

 

package com.common;

public class Common {
       public static final String OFFICE_EXCEL_2003_POSTFIX = "xls";
        public static final String OFFICE_EXCEL_2010_POSTFIX = "xlsx";
      
        public static final String EMPTY = "";
        public static final String POINT = ".";
        public static final String LIB_PATH = "lib";
        public static final String ITEM_INFO_XLS_PATH = LIB_PATH + "/item_info" + POINT + OFFICE_EXCEL_2003_POSTFIX;
        public static final String ITEM_INFO_XLSX_PATH = LIB_PATH + "/item_info" + POINT + OFFICE_EXCEL_2010_POSTFIX;
        public static final String NOT_EXCEL_FILE = " : Not the Excel file!";
        public static final String PROCESSING = "Processing...";
}
3:excel类

package com.excel;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFCell;
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.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.thymeleaf.expression.Calendars;

import com.common.Common;
import com.domain.ItemInfo;
import com.utils.Util;

public class ReadExcel {
    /**
     * read the Excel file
     * 
     * @param path
     *            the path of the Excel file
     * @return
     * @throws IOException
     * @throws ParseException
     */
    public List<ItemInfo> readExcel(String path) throws IOException, ParseException {
        if (path == null || Common.EMPTY.equals(path)) {
            return null;
        } else {
            String postfix = Util.getPostfix(path);
            if (!Common.EMPTY.equals(postfix)) {
                if (Common.OFFICE_EXCEL_2003_POSTFIX.equals(postfix)) {
                    return readXls(path);
                } else if (Common.OFFICE_EXCEL_2010_POSTFIX.equals(postfix)) {
                    return readXlsx(path);
                }
            } else {
                System.out.println(path + Common.NOT_EXCEL_FILE);
            }
        }
        return null;
    }

    /**
     * Read the Excel 2010
     * 
     * @param path
     *            the path of the excel file
     * @return
     * @throws IOException
     * @throws ParseException
     */
    
    public List<ItemInfo> readXlsx(String path) throws IOException, ParseException {
        System.out.println(Common.PROCESSING + path);
        // String replace = path.replace("xlsx", "xls");
        InputStream is = new FileInputStream(path);
        XSSFWorkbook xssfWorkbook = new XSSFWorkbook(is);
        ItemInfo itemInfo = null;
        List<ItemInfo> list = new ArrayList<ItemInfo>();
        // Read the Sheet
        for (int numSheet = 0; numSheet < xssfWorkbook.getNumberOfSheets(); numSheet++) {
            XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(numSheet);
            if (xssfSheet == null) {
                continue;
            }
            // Read the Row
            for (int rowNum = 1; rowNum <= xssfSheet.getLastRowNum(); rowNum++) {
                XSSFRow xssfRow = xssfSheet.getRow(rowNum);
                if (xssfRow != null) {
                    itemInfo = new ItemInfo();
                    XSSFCell id = xssfRow.getCell(0);
                    XSSFCell code = xssfRow.getCell(1);
                    XSSFCell name = xssfRow.getCell(2);
                    XSSFCell price = xssfRow.getCell(3);
                    XSSFCell isactive = xssfRow.getCell(4);
                    XSSFCell createtime = xssfRow.getCell(5);
                    XSSFCell updatetime = xssfRow.getCell(6);
                    

                    itemInfo.setId(doubleFormatInt(id));
                    itemInfo.setCode(getValue(code));
                    itemInfo.setName(getValue(name));
                    itemInfo.setPrice(new BigDecimal(getValue(price)));
                    itemInfo.setIsActive(doubleFormatInt(isactive));
                    itemInfo.setCreateTime(dataFormatString(createtime));
                    itemInfo.setUpdateTime(dataFormatString(updatetime));
                    list.add(itemInfo);
                }
            }
        }
        return list;
    }

    /**
     * Read the Excel 2003-2007
     * 
     * @param path
     *            the path of the Excel
     * @return
     * @throws IOException
     */
    @SuppressWarnings("deprecation")
    public List<ItemInfo> readXls(String path) throws IOException {
        System.out.println(Common.PROCESSING + path);
        InputStream is = new FileInputStream(path);
        HSSFWorkbook hssfWorkbook = new HSSFWorkbook(is);
        ItemInfo itemInfo = null;
        List<ItemInfo> list = new ArrayList<ItemInfo>();
        // Read the Sheet
        for (int numSheet = 0; numSheet < hssfWorkbook.getNumberOfSheets(); numSheet++) {
            HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(numSheet);
            if (hssfSheet == null) {
                continue;
            }
            // Read the Row
            for (int rowNum = 1; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
                HSSFRow hssfRow = hssfSheet.getRow(rowNum);
                if (hssfRow != null) {
                    itemInfo = new ItemInfo();
                    HSSFCell id = hssfRow.getCell(0);
                    HSSFCell code = hssfRow.getCell(1);
                    HSSFCell name = hssfRow.getCell(2);
                    HSSFCell price = hssfRow.getCell(3);
                    HSSFCell isactive = hssfRow.getCell(4);
                    HSSFCell createtime = hssfRow.getCell(5);
                    HSSFCell updatetime = hssfRow.getCell(6);
                    itemInfo.setId(Integer.parseInt(getValue(id)));
                    itemInfo.setCode(getValue(code));
                    itemInfo.setName(getValue(name));
                    itemInfo.setPrice(new BigDecimal(getValue(price)));
                    itemInfo.setIsActive(Integer.parseInt(getValue(isactive)));
                    itemInfo.setCreateTime(new Date(getValue(createtime)));
                    itemInfo.setUpdateTime(new Date(getValue(updatetime)));
                    list.add(itemInfo);
                }
            }
        }
        return list;
    }

    @SuppressWarnings("static-access")
    private String getValue(XSSFCell xssfRow) {
        if (xssfRow.getCellType() == xssfRow.CELL_TYPE_BOOLEAN) {
            return String.valueOf(xssfRow.getBooleanCellValue());
        } else if (xssfRow.getCellType() == xssfRow.CELL_TYPE_NUMERIC) {
            return String.valueOf(xssfRow.getNumericCellValue());
        } else {
            return String.valueOf(xssfRow.getStringCellValue());
        }
    }

    @SuppressWarnings("static-access")
    private String getValue(HSSFCell hssfCell) {
        if (hssfCell.getCellType() == hssfCell.CELL_TYPE_BOOLEAN) {
            return String.valueOf(hssfCell.getBooleanCellValue());
        } else if (hssfCell.getCellType() == hssfCell.CELL_TYPE_NUMERIC) {
            return String.valueOf(hssfCell.getNumericCellValue());
        } else {
            return String.valueOf(hssfCell.getStringCellValue());
        }
    }

    /**
     * 处理excel时间类型,处理的结果字符串并转换为data
     * 
     * @param xssfCell
     * @return
     * @throws ParseException
     */
    
    private Date dataFormatString(XSSFCell xssfCell) throws ParseException {
        String guarantee_date = "";
        Date date = new Date();
        // 判断是否为日期类型
        if (0 == xssfCell.getCellType()) {
            if (DateUtil.isCellDateFormatted(xssfCell)) {
                // 用于转化为日期格式
                Date d = xssfCell.getDateCellValue();
                DateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                guarantee_date = formater.format(d);
                date = formater.parse(guarantee_date);

            }
        }
        return date;
    }

    /**
     * excel整数处理方法
     * 
     * @param xssfCell
     */
    public int doubleFormatInt(XSSFCell xssfCell) {
        Integer count = 0;
        // System.out.println("入库数量:"+xssfCell);
        if (xssfCell.toString().indexOf(".") >= 0) {
            // System.out.println(". 位数: "+ xssfCell.toString().indexOf("."));
            String s = xssfCell.toString().substring(0, xssfCell.toString().indexOf("."));
            count = Integer.valueOf(s);
            //System.out.println(count);
        }
        return count;
    }

}
4:实体类:

package com.domain;

import java.math.BigDecimal;
import java.util.Date;

public class ItemInfo {
    private Integer id;

    private String code;

    private String name;

    private BigDecimal price;

    private Integer isActive;

    private Date createTime;

    private Date updateTime;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code == null ? null : code.trim();
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name == null ? null : name.trim();
    }

    public BigDecimal getPrice() {
        return price;
    }

    public void setPrice(BigDecimal price) {
        this.price = price;
    }

    public Integer getIsActive() {
        return isActive;
    }

    public void setIsActive(Integer isActive) {
        this.isActive = isActive;
    }

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    public Date getUpdateTime() {
        return updateTime;
    }

    public void setUpdateTime(Date updateTime) {
        this.updateTime = updateTime;
    }
}

5:测试类:

package com.client;

import java.io.IOException;
import java.text.ParseException;
import java.util.List;

import com.common.Common;
import com.domain.ItemInfo;
import com.excel.ReadExcel;

public class Client {
    public static void main(String[] args) throws IOException, ParseException {
                 String excel2003_2007 = Common.ITEM_INFO_XLS_PATH;
                 String excel2010 = Common.ITEM_INFO_XLSX_PATH;
                 // read the 2003-2007 excel
                /* List<ItemInfo> list = new ReadExcel().readExcel(excel2003_2007);
                 if (list != null) {
                     for (ItemInfo itemInfo : list) {
                         System.out.println("Id. : " + itemInfo.getId() + ", name : " + itemInfo.getName() +
                                 ", code : " + itemInfo.getCode() + ", price : " + itemInfo.getPrice());
                     }
                 }*/
                 System.out.println("======================================");
                 // read the 2010 excel
                 List<ItemInfo> list1 = new ReadExcel().readExcel(excel2010);
                 if (list1 != null) {
                     for (ItemInfo itemInfo : list1) {
                         System.out.println("Id. : " + itemInfo.getId() + ", name : " + itemInfo.getName() +
                                 ", code : " + itemInfo.getCode() + ", price : " + itemInfo.getPrice());
                    }
                 }
             }
}
 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值