1. 程式人生 > >Excle 匯入匯出

Excle 匯入匯出

pom.依賴

<!--poi-->
	<dependency>
		<groupId>org.apache.poi</groupId>
		<artifactId>poi</artifactId>
		<version>3.17</version>
	</dependency>

匯入工具類

package com.zsCat.common.utils;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
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.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
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.xssf.usermodel.XSSFWorkbook;

public class ParseExcelUtils {
	 public static List<String[]> rosolveFile(InputStream is, String suffix,
				int startRow) throws IOException, FileNotFoundException {
			Workbook xssfWorkbook = null;
			if ("xls".equals(suffix)) {
				xssfWorkbook = new HSSFWorkbook(is);
			} else if ("xlsx".equals(suffix)) {
				xssfWorkbook = new XSSFWorkbook(is);
			}
			Sheet xssfSheet = xssfWorkbook.getSheetAt(0);
			if (xssfSheet == null) {
				return null;
			}
			ArrayList<String[]> list = new ArrayList<String[]>();
			int lastRowNum = xssfSheet.getLastRowNum();
			for (int rowNum = startRow; rowNum <= lastRowNum; rowNum++) {
				if (xssfSheet.getRow(rowNum) != null) {
					Row xssfRow = xssfSheet.getRow(rowNum);
					short firstCellNum = xssfRow.getFirstCellNum();
					short lastCellNum = xssfRow.getLastCellNum();
					if (firstCellNum != lastCellNum) {
						String[] values = new String[lastCellNum];
						for (int cellNum = firstCellNum; cellNum < lastCellNum; cellNum++) {
							Cell xssfCell = xssfRow.getCell(cellNum);
							if (xssfCell == null) {
								values[cellNum] = "";
							} else {
								values[cellNum] = parseExcel(xssfCell);
							}
						}
						list.add(values);
					}
				}
			}
			return list;
		}
		public static String parseExcel(Cell cell) {
			DecimalFormat decimalFormat = new DecimalFormat("#.##");
			String result = new String();
			switch (cell.getCellType()) {
			case HSSFCell.CELL_TYPE_NUMERIC:// 數字型別
				if (HSSFDateUtil.isCellDateFormatted(cell)) {// 處理日期格式、時間格式
					SimpleDateFormat sdf = null;
					if (cell.getCellStyle().getDataFormat() == HSSFDataFormat
							.getBuiltinFormat("h:mm")) {
						sdf = new SimpleDateFormat("HH:mm");
					} else {// 日期
						sdf = new SimpleDateFormat("yyyy-MM-dd");
					}
					Date date = cell.getDateCellValue();
					result = sdf.format(date);
				} else if (cell.getCellStyle().getDataFormat() == 58) {
					// 處理自定義日期格式:m月d日(通過判斷單元格的格式id解決,id的值是58)
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
					double value = cell.getNumericCellValue();
					Date date = org.apache.poi.ss.usermodel.DateUtil
							.getJavaDate(value);
					result = sdf.format(date);
				} else {
					double value = cell.getNumericCellValue();
					CellStyle style = cell.getCellStyle();

					DecimalFormat format = new DecimalFormat();
					String temp = style.getDataFormatString();
					// 單元格設定成常規
					if (temp.equals("General")) {
						format.applyPattern("#");
					}
					result = decimalFormat.format((cell.getNumericCellValue()));
				}
				break;
			case HSSFCell.CELL_TYPE_STRING:// String型別
				result = cell.getRichStringCellValue().toString();
				break;
			case HSSFCell.CELL_TYPE_BLANK:
				result = "";
			default:
				result = "";
				break;
			}
			return result;
		}
}

模板驗證工具類

package com.zscat.shop.utils;


public class ExcleTempletValidateUtils {

    /**驗證匯入的excle資料的表頭與模板資料是否相等
     *
     * @param incomingDataArray  匯入的excle資料
     * @param excleTemplet   驗證模板陣列
     * @return
     */
    public static boolean toExcleValidate(String[] incomingDataArray,String[] excleTemplet){
        if(incomingDataArray==null||excleTemplet==null){
            return  false;
        }
        if(incomingDataArray.length!=excleTemplet.length&&incomingDataArray.length<1&&excleTemplet.length<1){
            return  false;
        }
        for(int i=0;i<incomingDataArray.length;i++){
            if(!incomingDataArray[i].equals(excleTemplet[i])){
                return false;
            }
        }
        return true;
    }
}

匯入方法

 //匯入Excel
    @ResponseBody
    @PostMapping("/parseExcel")
    public R parseExcel(MultipartFile file) {
        int tempNum=0;
        int length=0;
        try {
            String fileName = file.getOriginalFilename();
            String prefix = fileName.substring(fileName.lastIndexOf(".") + 1);
            List<String[]> list = ParseExcelUtils.rosolveFile(file.getInputStream(), prefix, 1);  //獲取每行的資料
            List<String[]> listValidete = ParseExcelUtils.rosolveFile(file.getInputStream(), prefix, 0);  //獲取每行的資料
            length=list.size();
            if(listValidete!=null&&listValidete.size()>0){
                String[] strValidateClus=listValidete.get(0);
                String[] excleTemplet={"機構名稱","報價日期","供應商名稱","sku編號","sku名稱","品牌","單位","規格","稅率","無稅價","含稅價","銷售價"};
                if (!ExcleTempletValidateUtils.toExcleValidate(strValidateClus,excleTemplet)) {
                    return R.error("匯入資料的模板錯誤");
                }
            }
            if(length<1){
                return R.error("匯入資料為空");
            }
            int num = 0;
            List<SupplierQuotationsExcleInpotVo> goodsExcleInpotVoList = new ArrayList<SupplierQuotationsExcleInpotVo>();//商品模板實體集合
            List<String> skuNoList = new ArrayList<String>(); //SKU編碼集合
            for (int i = 0; i < list.size(); i++) {
                String[] arr = list.get(i);
                if (arr.length < 12) {
                    return R.error("第" + (i + 2) + "條資料的沒有填寫完善或著可能是空行");
                }
                String deptName = arr[0].trim();//機構名稱
                String offerDate = arr[1].trim();//報價日期
                String supplierName = arr[2].trim();//供應商名稱
                String skuNo = arr[3].trim();//sku編號
                String goodsName= arr[4].trim();//sku名稱
                String brand  = arr[5].trim();//品牌
                String unit = arr[6].trim();//單位
                String goodsSpec = arr[7].trim();//規格
                String taxRate = arr[8].trim();//稅率
                String taxFreePrice = arr[9].trim();//無稅價
                String freePrice = arr[10].trim();//採購價(含稅)
                String salePrice = arr[11].trim();//銷售價(含稅)
                if(skuNo==null||skuNo.equals("")){
                    return R.error("第"+(i+1)+"條資料的【sku編碼】未填寫");
                }
                if(deptName==null||deptName.equals("")){
                    return R.error("sku編碼為【"+skuNo+"】的【機構名稱】未填寫");
                }
                if(goodsName==null||goodsName.equals("")){
                    return R.error("sku編碼為【"+skuNo+"】的【商品名稱】未填寫");
                }
                if(supplierName==null||supplierName.equals("")){
                    return R.error("sku編碼為【"+skuNo+"】的【供應商】未填寫");
                }
                if(brand==null||brand.equals("")){
                    return R.error("sku編碼為【"+skuNo+"】的【品牌】未填寫");
                }
                if(unit==null||unit.equals("")){
                    return R.error("sku編碼為【"+skuNo+"】的【單位】未填寫");
                }
                if(taxRate==null||taxRate.equals("")){
                    return R.error("sku編碼為【"+skuNo+"】的【稅率】未填寫");
                }
                Map<String,Object> map=new HashMap<>();
                map.put("deptName",deptName);
                map.put("type","供應鏈公司");
                SupplierQuotationsExcleInpotVo  vo=new SupplierQuotationsExcleInpotVo();//實體
                List<DeptDO> dds=deptService.list(map);
                if(dds!=null&&dds.size()>0){
                    vo.setDeptName(deptName);
                    vo.setDeptNo(dds.get(0).getDeptNo());
                    dds=null;
                }else {
                    dds=null;
                    return R.error("機構名稱不對,"+deptName+"機構屬性為供應鏈公司");
                }
                if(offerDate!=null&&offerDate!=""){
                    Date date = null;
                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                    try{
                        vo.setOfferDate(df.parse(offerDate));
                    }catch (ParseException e){
                        return R.error("時間格式錯誤,應該格式為‘2018-08-08’");
                    }
                }else{
                    return R.error("sku編碼為【"+skuNo+"】的報價日期未填寫");
                }
                map.clear();
                map.put("supplier",supplierName);
                List<SupplierDirectoryDO> ss=supplierDirectoryService.list(map);
                if(ss!=null&&ss.size()>0){
                    vo.setSupplierName(supplierName);
                    vo.setSupplierNo(ss.get(0).getSupplierNo()+"");
                }else {
                    ss=null;
                    return R.error(supplierName+":供應商不存在");
                }
                //新新增驗證
                SupplierDirectoryDO so =supplierDirectoryService.get(ss.get(0).getSupplierNo().intValue());
                ss=null;
                List<String> listtt=new ArrayList<>();
                if(so.getServeCity()!=null&&!"".equals(so.getServeCity())){
                    if(so.getServeCity().indexOf(",")!=-1){
                        String[] s=so.getServeCity().split(",");
                        for(int p=0;p<s.length;p++){
                            listtt.add(s[p].trim());
                        }
                    }else {
                        listtt.add(so.getServeCity().trim());
                    }
                }else{
                    return R.error(supplierName+":沒有城市屬性");
                }
                List<String> lists=new ArrayList<>();
                if(listtt.size()>0){
                    for(String ll:listtt){
                        lists.add(areaService.getlistNoByListName(ll));
                    }
                }
                Map<String,Object> params=new HashMap<>();
                params.put("cityNos",lists);
                List<SupplierQuotationsDetailedDO> supplierQuotationsDetailedList = supplierQuotationsDetailedService.listsku(params);
                SkuDO sdo=skuService.findSkuBySkuNo(skuNo);
                if(sdo!=null){
                   if(supplierQuotationsDetailedList!=null&&supplierQuotationsDetailedList.size()>0){
                       for (SupplierQuotationsDetailedDO sdodd:supplierQuotationsDetailedList){
                           if(sdodd.getSkuNo().equals(sdo.getSkuNo())){
                               vo.setSkuNo(skuNo);
                               vo.setGoodsName(goodsName);
                               vo.setGoodsSpec(goodsSpec);
                           }
                       }
                   }
                }else {
                    sdo=null;
                    return R.error("編號為:【"+skuNo+"】的sku,沒有分配此【供應商服務的城市】");
                }
                if(vo.getSkuNo()==null||"".equals(vo.getSkuNo())){
                    return R.error("編號為:【"+skuNo+"】的sku,不存在,或者沒有分配【供應商服務的城市】");
                }
                map.clear();
                map.put("brand",brand);
                List<BrandDirectoryDO> bs=brandDirectoryService.list(map);
                if(bs!=null&&bs.size()>0){
                    vo.setBrand(brand);
                    vo.setBrandNo(bs.get(0).getBrandNo()+"");
                    bs=null;
                }else{
                    bs=null;
                    return R.error("【"+brand+"】的品牌,不存在");
                }
                map.clear();
                map.put("unit",unit);
                List<UnitDirectoryDO> us=unitDirectoryService.list(map);
                if(us!=null&&us.size()>0){
                    vo.setUnit(unit);
                }
                if(taxFreePrice!=null&&taxFreePrice!=""&&freePrice!=null&&freePrice!=""){
                    return R.error("編號為:【"+skuNo+"】的sku的無稅價和稅價只能填一個");
                }else  if(taxFreePrice!=null&&taxFreePrice!=""){
                    if(taxFreePrice.matches("^[0-9]+(.[0-9]+)?$")){
                        vo.setTaxFreePrice(new BigDecimal(taxFreePrice));
                    }else {
                        return R.error("編號為:【"+skuNo+"】的sku的價錢"+"【"+taxFreePrice+"】不是數字格式");
                    }
                }else  if(freePrice!=null&&freePrice!=""){
                    if(freePrice.matches("^[0-9]+(.[0-9]+)?$")){
                        vo.setFreePrice(new BigDecimal(freePrice));
                    }else {
                        return R.error("編號為:【"+skuNo+"】的sku的價錢"+"【"+freePrice+"】不是數字格式");
                    }
                }
                if(taxRate!=null&&taxRate!=""){
                    if(taxRate.matches("^[0-9]+(.[0-9]+)?$")){
                        vo.setTaxRate(new BigDecimal(taxRate));
                    }else {
                        return R.error("編號為:【"+skuNo+"】的sku的價錢"+"【"+freePrice+"】不是數字格式");
                    }
                }else {
                    return R.error("編號為:【"+skuNo+"】的稅率不能為空");
                }
                if(skuNoList.contains(skuNo)){
                    return R.error("編號為:【"+skuNo+"】的sku重複匯入");
                }
                if(salePrice==null||salePrice.equals("")){
                    return R.error("編號為:【"+skuNo+"】的銷售價為空");
                }else if(salePrice.matches("^[0-9]+(.[0-9]+)?$")){
                    vo.setSalePrice(new BigDecimal(salePrice));
                }else {
                    return R.error("編號為:【"+skuNo+"】的sku的價錢"+"【"+salePrice+"】不是數字格式");
                }
                goodsExcleInpotVoList.add(vo);
            }
            if(goodsExcleInpotVoList.size()>0){
                SupplierQuotationsDO sqo=new SupplierQuotationsDO();
                sqo.setDr("0");
                sqo.setCreateBy(ShiroUtils.getUser().getUsername());
                sqo.setCreateNo(ShiroUtils.getUser().getUserNo());
                sqo.setCreateTime(new Date());
                sqo.setUpdateBy(ShiroUtils.getUser().getUsername());
                sqo.setUpdateNo(ShiroUtils.getUser().getUserNo());
                sqo.setUpdateTime(sqo.getUpdateTime());
                Map<String,Object> map=new HashMap<>();
                map.put("offset",0);
                map.put("limit",1);
                map.put("deptNo",goodsExcleInpotVoList.get(0).getDeptNo());
                map.put("supplierNo",goodsExcleInpotVoList.get(0).getSupplierNo());
                List<SupplierQuotationsDO> sss=supplierQuotationsService.list(map);
                String tempOfferNo="";
                String temp="";
                if(sss!=null&&sss.size()>0){  //機構存在
                    tempOfferNo=sss.get(0).getOfferNo();
                    String vnum=sss.get(0).getVersionNumber();
                    temp=vnum.substring(3,vnum.length());
                    temp="v1."+(new Integer(temp)+1)+"";

                }else{   //機構不存在
                    map.clear();
                    map.put("offset",0);
                    map.put("limit",1);
                    List<SupplierQuotationsDO> sid=supplierQuotationsService.list(map);
                    if(sid!=null&&sid.size()>0){
                        tempOfferNo="BJD"+SerialNumber.serial(sid.get(0).getOfferNo(),6);//BJD
                        temp="v1.0";
                    }else{
                        tempOfferNo="BJD000001";//BJD
                        temp="v1.0";
                    }
                }
                for(SupplierQuotationsExcleInpotVo so:goodsExcleInpotVoList){
                        so.setVersionNumber(temp);
                        so.setOfferNo(tempOfferNo);
                        sqo.setOfferDate(so.getOfferDate());
                        sqo.setOfferNo(so.getOfferNo());
                        sqo.setSupplierNo(so.getSupplierNo());
                        sqo.setSupplierName(so.getSupplierName());
                        sqo.setDeptName(so.getDeptName());
                        sqo.setDeptNo(so.getDeptNo());
                        sqo.setVersionNumber(so.getVersionNumber());
                }
                int offerId =supplierQuotationsService.saveVo(sqo);
                for(SupplierQuotationsExcleInpotVo so:goodsExcleInpotVoList){
                    SupplierQuotationsDetailedDO o=new SupplierQuotationsDetailedDO();
                    o.setDr("0");
                    o.setBrand(so.getBrand());
                    o.setBrandNo(so.getBrandNo());
                    o.setFreePrice(so.getFreePrice());
                    o.setGoodsName(so.getGoodsName());
                    o.setGoodsSpec(so.getGoodsSpec());
                    o.setOfferId(Long.valueOf(offerId+""));
                    o.setOfferNo(so.getOfferNo());
                    o.setSkuNo(so.getSkuNo());
                    o.setTaxFreePrice(so.getTaxFreePrice());
                    o.setTaxRate(so.getTaxRate());
                    o.setUnit(so.getUnit());
                    o.setVersionNumber(so.getVersionNumber());
                    o.setSalePrice(so.getSalePrice());
                   tempNum+=supplierQuotationsDetailedService.save(o);
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
            return R.error("出現異常,匯入失敗");
        }
        if(tempNum==length){
            return R.ok("匯入成功");
        }
        return R.error("匯入失敗");
    }

匯出方法

 /**
     * 刪除
     */
    @GetMapping("/downloadExcleById")
    @ResponseBody
    //@RequiresPermissions("base:supplierQuotations:batchRemove")
    public void updateVo(HttpServletResponse response, Long  id) throws IOException {
        if(id!=null){
            Map<String,Object> map=new HashMap<>();
            map.put("offerId",id);
            map.put("drs",123456);
            List<SupplierQuotationsDetailedDO> slist=supplierQuotationsDetailedService.list(map);
            String name = "供應商報價單匯出"+new Date().getTime();
            response.setContentType("octets/stream");
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(name.getBytes("gb2312"), "ISO8859-1") + ".xls");
            String[] headers = {"sku編號","sku名稱","品牌","單位","規格","稅率","無稅價","含稅價","銷售價"};
            OutputStream out = response.getOutputStream();
            // 宣告一個工作簿
            HSSFWorkbook workbook = new HSSFWorkbook();
            // 生成一個表格
            HSSFSheet sheet = workbook.createSheet(name);
            // 設定表格預設列寬度為15個字元
            sheet.setDefaultColumnWidth(20);
            // 產生表格標題行
            HSSFRow row00 = sheet.createRow(0);
            HSSFCell c00 = row00.createCell(0);
            c00.setCellValue(new HSSFRichTextString("供應商名稱:"));
            HSSFCell c01 = row00.createCell(1);
            c01.setCellValue(new HSSFRichTextString(supplierQuotationsService.get(id).getSupplierName()));
            //CellRangeAddress  物件的構造方法需要傳入合併單元格的首行、最後一行、首列、最後一列。
            CellRangeAddress cra0=new CellRangeAddress(0, 0, 1, 7);

            //合併單元格所使用的方法:
            sheet.addMergedRegion(cra0);
            // 產生表格標題行
            HSSFRow row1 = sheet.createRow(1);
            int o = 0;
            for(int i=0;i<headers.length;i++){
                row1.createCell(o++).setCellValue(headers[i].toString());
            }
            for (int i = 0; i < slist.size(); i++) {
                int k = 1;
                SupplierQuotationsDetailedDO DesignerQuotationDetailsDO = slist.get(i);
                row1 = sheet.createRow(i + 1+k);
                int j = 0;                           //     ==null?"":   ==null?"0":
                row1.createCell(j++).setCellValue(DesignerQuotationDetailsDO.getSkuNo()==null?"":DesignerQuotationDetailsDO.getSkuNo().toString());
                row1.createCell(j++).setCellValue(DesignerQuotationDetailsDO.getGoodsName()==null?"":DesignerQuotationDetailsDO.getGoodsName().toString());
                row1.createCell(j++).setCellValue(DesignerQuotationDetailsDO.getBrand()==null?"":DesignerQuotationDetailsDO.getBrand().toString());
                row1.createCell(j++).setCellValue(DesignerQuotationDetailsDO.getUnit()==null?"":DesignerQuotationDetailsDO.getUnit().toString());
                row1.createCell(j++).setCellValue(DesignerQuotationDetailsDO.getGoodsSpec()==null?"":DesignerQuotationDetailsDO.getGoodsSpec().toString());
                row1.createCell(j++).setCellValue(DesignerQuotationDetailsDO.getTaxRate()==null?"0":DesignerQuotationDetailsDO.getTaxRate().setScale(2,BigDecimal.ROUND_HALF_UP).toString());
                row1.createCell(j++).setCellValue(DesignerQuotationDetailsDO.getTaxFreePrice()==null?"0":DesignerQuotationDetailsDO.getTaxFreePrice().setScale(2,BigDecimal.ROUND_HALF_UP).toString());
                row1.createCell(j++).setCellValue(DesignerQuotationDetailsDO.getFreePrice()==null?"0":DesignerQuotationDetailsDO.getFreePrice().setScale(2,BigDecimal.ROUND_HALF_UP).toString());
                row1.createCell(j++).setCellValue(DesignerQuotationDetailsDO.getSalePrice()==null?"0":DesignerQuotationDetailsDO.getSalePrice().setScale(2,BigDecimal.ROUND_HALF_UP).toString());

            }
            try {
                workbook.write(out);
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                out.close();
            }
        }
    }