天天看點

java Excel導出以及讀取Excel資料                                             java  Excel導出:                             java 讀取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 {

    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;

public class TpolicyNauto{

    //private Long id;

    private String reqTime;

    private String reqNo;

    private String sysCode;

    private String transactionNo;

    private String policyNo;

    private String proposalNo;

    private String combinPolicy;

    private String comCode;

    private String collectionDate;

    private String classCode;

    private String className;

    private BigDecimal premiumFee;

    private BigDecimal commisionRate;

    private BigDecimal commisionFee;

    private BigDecimal kindRate;

    private Date createTime;

    private Date updateTime;

    public String getReqTime() {

        return reqTime;

    }

    public void setReqTime(String reqTime) {

        this.reqTime = reqTime;

    }

    public String getReqNo() {

        return reqNo;

    }

    public void setReqNo(String reqNo) {

        this.reqNo = reqNo;

    }

    public String getSysCode() {

        return sysCode;

    }

    public void setSysCode(String sysCode) {

        this.sysCode = sysCode;

    }

    public String getTransactionNo() {

        return transactionNo;

    }

    public void setTransactionNo(String transactionNo) {

        this.transactionNo = transactionNo;

    }

    public String getPolicyNo() {

        return policyNo;

    }

    public void setPolicyNo(String policyNo) {

        this.policyNo = policyNo;

    }

    public String getProposalNo() {

        return proposalNo;

    }

    public void setProposalNo(String proposalNo) {

        this.proposalNo = proposalNo;

    }

    public String getCombinPolicy() {

        return combinPolicy;

    }

    public void setCombinPolicy(String combinPolicy) {

        this.combinPolicy = combinPolicy;

    }

    public String getComCode() {

        return comCode;

    }

    public void setComCode(String comCode) {

        this.comCode = comCode;

    }

    public String getCollectionDate() {

        return collectionDate;

    }

    public void setCollectionDate(String collectionDate) {

        this.collectionDate = collectionDate;

    }

    public String getClassCode() {

        return classCode;

    }

    public void setClassCode(String classCode) {

        this.classCode = classCode;

    }

    public String getClassName() {

        return className;

    }

    public void setClassName(String className) {

        this.className = className;

    }

    public BigDecimal getPremiumFee() {

        return premiumFee;

    }

    public void setPremiumFee(BigDecimal premiumFee) {

        this.premiumFee = premiumFee;

    }

    public BigDecimal getCommisionRate() {

        return commisionRate;

    }

    public void setCommisionRate(BigDecimal commisionRate) {

        this.commisionRate = commisionRate;

    }

    public BigDecimal getCommisionFee() {

        return commisionFee;

    }

    public void setCommisionFee(BigDecimal commisionFee) {

        this.commisionFee = commisionFee;

    }

    public BigDecimal getKindRate() {

        return kindRate;

    }

    public void setKindRate(BigDecimal kindRate) {

        this.kindRate = kindRate;

    }

    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;

    }

    private String isnewCar;

    public String getIsnewCar() {

        return isnewCar;

    }

    public void setIsnewCar(String isnewCar) {

        this.isnewCar = isnewCar;

    }

}

4:Controller類

    @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 {

         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 {

    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;

    }

    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;

    }

    @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());

        }

    }

    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;

    }

    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

                 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());

                    }

                 }

             }

}