上傳excel文件,導出excel模板實現

此功能上商品導入,分別有導入組別,品類,屬性(json字符串截取)等多功能多表實現。

導出功能,根據自定義需要的模板名稱生成可配置模板

controller調用前段路徑,然後導入/導出模板工具,service實現。

首先pom中導入excel jar包

        <!--exceljar-->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-excelant</artifactId>
            <version>4.1.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.17</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml-schemas</artifactId>
            <version>3.17</version>
        </dependency>

controller

package com.macro.mall.controller;

import com.macro.mall.common.api.CommonResult;
import com.macro.mall.service.IExcelService;
import com.macro.mall.util.ConstantUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Map;

/**
 * 上傳Excel導入商品
 *
 * @author gbl
 * date 2019年12月1日17:03:55
 */
@Controller
@Api(tags = "UploadController", description = "商品導入excel")
@RequestMapping("/upload")
public class UploadController {

    @Autowired
    private IExcelService iExcelService;

    private static String filenameTemp;

    /**
     * 上傳商品excel
     * @param file
     * @return
     */
    @RequestMapping(value = "/excel", method = RequestMethod.POST)
    @ApiOperation("上傳excel")
    @ResponseBody
    public Map<String, Object>  uploadExecl(@RequestParam("file") MultipartFile file) {
        return iExcelService.uploadExecl(file);
    }

    /**
     * 描述:下載導入模板
     * @throws Exception
     */
    @RequestMapping( value = "/downloadExcel", method = RequestMethod.GET )
    @ApiOperation("下載excel模板")
    @ResponseBody
    public CommonResult exportWhitelistTemplate(HttpServletResponse response) {
        iExcelService.exportWhitelistTemplate(response);
        return null;
    }

    @GetMapping("/errorFile")
    public ResponseEntity<FileSystemResource> downErrorFile(HttpServletRequest request) throws Exception {
        File path = new File(ResourceUtils.getURL("classpath:").getPath());
        if (!path.exists()) {
            path = new File("");
        }
        File upload = new File(path.getAbsolutePath() + ConstantUtil.STATIC_FRONTEND_PROJECT_TEMPLATE);
        if (!upload.exists()) {
            upload.mkdirs();
        }
        filenameTemp = java.net.URLDecoder.decode(upload.getAbsolutePath().replaceAll("!", ConstantUtil.NULL_STRING), ConstantUtil.UTF_8) + File.separator + ConstantUtil.IMPORT_ERROR_MESSAGE + ConstantUtil.WORD_TXT;
        File file = new File(filenameTemp);
        String userAgent = request.getHeader(ConstantUtil.USER_AGENT).toLowerCase();
        String fileName = ConstantUtil.ERRORFILENAME;
        if (userAgent.contains(ConstantUtil.MSIE) || userAgent.contains(ConstantUtil.LIKE_GECKO)) {
            fileName = URLEncoder.encode(fileName, ConstantUtil.UTF_8);
        } else {
            fileName = new String(fileName.getBytes(ConstantUtil.UTF_8), ConstantUtil.ISO_8859_1);
        }
        if (file.exists()) {
            return export(file, fileName);
        } else {
            return null;
        }

    }

    public ResponseEntity<FileSystemResource> export(File file, String fileName) {
        if (file == null) {
            return null;
        }
        HttpHeaders headers = new HttpHeaders();
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Content-Disposition", "attachment; filename=" + fileName + ".txt");
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");
        return ResponseEntity
                .ok()
                .headers(headers)
                .contentLength(file.length())
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(new FileSystemResource(file));
    }

}

service實現

package com.macro.mall.service;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @author gbl
 * @Description:
 * @date 2019年12月3日11:07:17
 */
public interface IExcelService {
    /**
     * 上傳execl
     * @param file
     * @return
     */
    Map<String, Object> uploadExecl(MultipartFile file);

    /**
     * 描述:下載導入模板
     * @param response
     */
    void exportWhitelistTemplate(HttpServletResponse response);
}

serivceImpl實現

package com.macro.mall.service.impl;

import com.macro.mall.bo.MallContext;
import com.macro.mall.common.api.CommonResult;
import com.macro.mall.common.api.ResultCode;
import com.macro.mall.dao.PmsProductAttributeValueDao;
import com.macro.mall.dto.GoodsListExcelVO;
import com.macro.mall.mapper.PmsProductMapper;
import com.macro.mall.mapper.PmsSkuStockMapper;
import com.macro.mall.model.*;
import com.macro.mall.service.IExcelService;
import com.macro.mall.service.PmsProductGroupService;
import com.macro.mall.service.PmsProductVarietyService;
import com.macro.mall.util.ConstantUtil;
import com.macro.mall.util.EntityUtils;
import com.macro.mall.util.ExcelUtils;
import com.macro.mall.util.ImportExcelV2Util;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.codehaus.jettison.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author gbl
 * @Description:
 * @date 2019年12月1日17:43:43
 */
@Service
@Slf4j
public class ExcelUploadImpl implements IExcelService {


    @Autowired
    private PmsProductMapper productMapper;

    @Autowired
    private PmsSkuStockMapper pmsSkuStockMapper;

    @Autowired
    private PmsProductVarietyService iVarietyService;

    @Autowired
    private PmsProductGroupService pmsProductGroupService;

    @Autowired
    private PmsProductAttributeValueDao productAttributeValueDao;

    /**
     *   判斷小數點後2位的數字的正則表達式
     */
    private static Pattern pattern=Pattern.compile("^(([1-9]{1}\\d*)|([0]{1}))(\\.(\\d){0,2})?$");

    @Override
    public Map<String, Object> uploadExecl(MultipartFile file) {
        Map<String, Object> resMap = new HashMap<>();
        // 存放解析完的excel數據
        List<Map<String, Object>> importList = new ArrayList<Map<String, Object>>();
        // 存放解析完的標題數據
        Map<String, Object> titleStringMap = new HashMap<String, Object>();
        String title = null;
        // 聲明並初始化Excel文件中列名的集合
        List<String> colList = new ArrayList<String>();
        // 以下列名順序需要與Excel文件中列名順序匹配
        String[] titleArray = ConstantUtil.ANY_CONSTANT_IMPORT_TITLEVAR.split(ConstantUtil.DOUHAO);
        colList = Arrays.asList(titleArray);
        // 判斷導入的文件是否爲空
        if (null != file) {
            // 驗證導入文件標題是否與導入模板匹配
            try {
                titleStringMap = ImportExcelV2Util.getImportExcelTitle(ConstantUtil.ANY_CONSTANT_IMPORT_DATAROW, file.getInputStream(),
                        ConstantUtil.ANY_CONSTANT_IMPORT_COUNTCOL, null);
                if (null != titleStringMap) {
                    // 判斷是否有錯誤消息寫入Map中
                    if (null == titleStringMap.get(ConstantUtil.ERRORMSG)) {
                        // 獲取標題
                        title = String.valueOf(titleStringMap.get(ConstantUtil.TITLESTRING));
                        // 判斷導入標題是否與模板標題匹配
                        if (ConstantUtil.ANY_CONSTANT_IMPORT_TITLE.equals(title)) {
                            // 將導入的Excel文件內容存儲到List中
                            importList = ImportExcelV2Util.doImmportExcel(ConstantUtil.ANY_CONSTANT_IMPORT_DATAROW, file.getInputStream(),
                                    ConstantUtil.ANY_CONSTANT_IMPORT_COUNTCOL, colList);
                            if (!importList.isEmpty()) {
                                // 調用驗證方法
                                resMap = validateXcjh(importList);
                                // 通過校驗,執行保存操作
                                if (resMap.get(ConstantUtil.STATUS).equals(ConstantUtil.STATUS_ZERO)) {
                                    @SuppressWarnings("unchecked")
                                    List<Map<String, Object>> paramList = (List<Map<String, Object>>) resMap.get("data");
                                    List<PmsProduct> pmsProducts = EntityUtils.map2List(paramList, PmsProduct.class);
                                    //存放分組、品類
                                    List<GoodsListExcelVO> goodsListVOList =EntityUtils.map2List(paramList, GoodsListExcelVO.class);

                                    //todo 關聯分組 和品類
                                    for(int i = 0; i < goodsListVOList.size(); i++){
                                        PmsProductVariety variety=iVarietyService.selectAllName(goodsListVOList.get(i).getVname());
                                        if (variety == null) {
                                            resMap.put(ConstantUtil.MSG, ConstantUtil.COMMON_VNAME);
                                            return resMap;
                                        }
                                        pmsProducts.get(i).setProductVarietyId(variety.getId());
                                        PmsProductGroup group=pmsProductGroupService.selectAllName(goodsListVOList.get(i).getGname());
                                        if (group == null) {
                                            resMap.put(ConstantUtil.MSG, ConstantUtil.COMMON_GNAME);
                                            return resMap;
                                        }
                                        pmsProducts.get(i).setProductGroupId(group.getId());
                                    }
                                    //todo 添加
//                                    int insert = productMapper.insertSelective(pmsProducts);

                                    //導入屬性  pms_sku_stock表
                                    PmsSkuStock pmsSkuStock = new PmsSkuStock();
                                    for (GoodsListExcelVO listExcelVO:goodsListVOList) {
                                        String specs = listExcelVO.getSpecs();
                                        //規格爲null  設置單規格屬性
                                        if(StringUtils.isBlank(specs)){
                                            for (PmsProduct pmsProduct:pmsProducts) {
                                                PmsSkuStock pmsSkuStock1 = new PmsSkuStock();
                                                pmsSkuStock1.setProductId(pmsProduct.getId());
                                                pmsSkuStock1.setSkuCode(pmsProduct.getHisenseCoding());
                                                pmsSkuStock1.setPrice(pmsProduct.getPrice());
                                                pmsSkuStock1.setPic(pmsProduct.getPic());
                                                pmsSkuStock1.setSale(pmsProduct.getSale());
                                            }
                                        }
                                        JSONArray jsonArray = null;
                                        jsonArray = new JSONArray(specs);
                                        Object price = jsonArray.getJSONObject(0).get("price");
                                        BigDecimal prices=new BigDecimal(String.valueOf(price));
                                        pmsSkuStock.setSp1(String.valueOf(jsonArray.getJSONObject(0).get("sp1")));
                                        pmsSkuStock.setSp2(String.valueOf(jsonArray.getJSONObject(0).get("sp2")));
                                        pmsSkuStock.setSp3(String.valueOf(jsonArray.getJSONObject(0).get("sp3")));
                                        pmsSkuStock.setPic(String.valueOf(jsonArray.getJSONObject(0).get("pic")));
                                        pmsSkuStock.setPrice(prices);
                                        pmsSkuStock.setSkuCode(String.valueOf(jsonArray.getJSONObject(0).get("skuCode")));
                                        pmsSkuStockMapper.insert(pmsSkuStock);
                                    }
                                    //添加商品
                                    for (PmsProduct pmsProduct : pmsProducts) {
                                        pmsProduct.setTenantId(MallContext.GetTenantid());
                                        pmsProduct.setCreateTime(new Date());
                                        pmsProduct.setUpdateTime(new Date());
                                        productMapper.insertSelective(pmsProduct);
                                    }
                                }
                            }
                        } else {
                            resMap.put(ConstantUtil.STATUS, ConstantUtil.STATUS_ZERO);
                            resMap.put(ConstantUtil.MSG, ConstantUtil.IMPORTEXCEL_TITLE_ERROR);
                        }
                    } else {
                        resMap.put(ConstantUtil.STATUS, ConstantUtil.STATUS_ZERO);
                        resMap.put(ConstantUtil.MSG, titleStringMap.get(ConstantUtil.ERRORMSG));
                    }
                } else {
                    resMap.put(ConstantUtil.STATUS, ConstantUtil.STATUS_ZERO);
                    resMap.put(ConstantUtil.MSG, ConstantUtil.IMPORTEXCEL_TITLE_NULL);
                }
            } catch (Exception e) {
                e.printStackTrace();
                resMap.put(ConstantUtil.STATUS, ConstantUtil.STATUS_ONE);
                resMap.put(ConstantUtil.MSG, ConstantUtil.IMPORTEXCEL_FAILE);
            }
        }
        return resMap;
    }

    @Override
    public void exportWhitelistTemplate(HttpServletResponse response) {
        try {
//            String time = "23456";
            String excelName = java.net.URLEncoder.encode("商品導入模板-", "UTF-8");
            String[] handers = {"商品類型(實物0/虛擬1)", "商品條碼","商品名稱","商品品類","商品組別","商品編碼","海信編碼","進貨價","掛牌價","稅收編碼","銷項稅(%)","進項稅(%)","包裝規格","商品屬性","商品數量","計量單位","商品重量(克)"};
            // 1導入硬盤
            ExcelUtils.exportExcelUsers(response, handers, excelName);
        } catch (Exception e) {
            e.printStackTrace();
            CommonResult.fail((int) ResultCode.FAILED.getCode(), "導出失敗");
        }
    }

    /**
     * 校驗商品數據格式
     *
     * @param paramList 導入的商品數據
     * @return datas數據
     * @throws Exception
     */
    public Map<String, Object> validateXcjh(List<Map<String, Object>> paramList) throws Exception {
        // 用來提示用戶第幾行有問題
        int i = 0;
        //異常刪除數組
        int j = -1;
        // IP正則表達式
        String reg = ConstantUtil.IPREG;
        Pattern pattern = Pattern.compile(reg);
        Map<String, Object> resMap = new HashMap<>();
        // 存放錯誤提示消息
        String errorMsg = ConstantUtil.NULL_STRING;
        List<Map<String, Object>> removeList = new ArrayList<Map<String, Object>>();
        // 校驗數據
        for (Map<String, Object> rowMap : paramList) {
            // 第i行
            i++;
            j++;
            // 獲取sheet頁名稱
            String sheetName = String.valueOf(rowMap.get(ConstantUtil.SHEETNAME));
            // 商品類型
            String virtualGoods = String.valueOf(rowMap.get("virtualGoods"));
            // 商品條碼
            String barCode = String.valueOf(rowMap.get("barCode"));
            // 商品名稱
            String name = String.valueOf(rowMap.get("name"));
            // 商品品類
            String vname = String.valueOf(rowMap.get("vname"));
            // 商品組別
            String gname = String.valueOf(rowMap.get("gname"));
            // 商品編碼
            String productSn = String.valueOf(rowMap.get("productSn"));
            // 海信編碼
            String hisenseCoding = String.valueOf(rowMap.get("hisenseCoding"));
            // 進貨價
            String purchasePrice = String.valueOf(rowMap.get("purchasePrice"));
            // 掛牌價
            String price = String.valueOf(rowMap.get("price"));
            // 稅收編碼
            String codingTax = String.valueOf(rowMap.get("codingTax"));
            // 銷項稅
            String taxOutput = String.valueOf(rowMap.get("taxOutput"));
            // 進項稅
            String taxRate = String.valueOf(rowMap.get("taxRate"));
            // 包裝規格
            String packingCoefficient = String.valueOf(rowMap.get("packingCoefficient"));
            // 商品屬性
            String specs = String.valueOf(rowMap.get("specs"));
            // 商品數量
            String stock = String.valueOf(rowMap.get("stock"));
            // 計量單位
            String unit = String.valueOf(rowMap.get("unit"));
            // 商品重量
            String weight = String.valueOf(rowMap.get("weight"));

            // 校驗商品類型
            if (StringUtils.isEmpty(virtualGoods)) {
                errorMsg = errorMsg + sheetName + ConstantUtil.MESSAGE_DE_DI + i + "行,商品類型不能爲空;" + ConstantUtil.HUANHANG;
            } else if (virtualGoods.length() > 1) {
                errorMsg = errorMsg + sheetName + ConstantUtil.MESSAGE_DE_DI + i + "行,商品類型不能超過1位;" + ConstantUtil.HUANHANG;
            }

            // 校驗商品條碼
            if (StringUtils.isEmpty(barCode)) {
                errorMsg = errorMsg + sheetName + ConstantUtil.MESSAGE_DE_DI + i + "行,商品條碼不能爲空;" + ConstantUtil.HUANHANG;
            } else if (barCode.length() > 40) {
                errorMsg = errorMsg + sheetName + ConstantUtil.MESSAGE_DE_DI + i + "行,商品條碼不能超過40位;" + ConstantUtil.HUANHANG;
            }

            // 校驗商品名稱
            if (StringUtils.isEmpty(name)) {
                errorMsg = errorMsg + sheetName + ConstantUtil.MESSAGE_DE_DI + i + "行,商品名稱不能爲空;" + ConstantUtil.HUANHANG;
            } else if (name.length() > 60) {
                errorMsg = errorMsg + sheetName + ConstantUtil.MESSAGE_DE_DI + i + "行,商品名稱不能超過60位;" + ConstantUtil.HUANHANG;
            } else if (isConSpeChar(name)){
                errorMsg = errorMsg + sheetName + ConstantUtil.MESSAGE_DE_DI + i + "行,商品名稱不能有特殊字符;" + ConstantUtil.HUANHANG;
            }

            // 校驗商品品類
            if (StringUtils.isEmpty(vname)) {
                errorMsg = errorMsg + sheetName + ConstantUtil.MESSAGE_DE_DI + i + "行,商品品類不能爲空;" + ConstantUtil.HUANHANG;
            } else if (vname.length() > 20) {
                errorMsg = errorMsg + sheetName + ConstantUtil.MESSAGE_DE_DI + i + "行,商品品類不能超過20位;" + ConstantUtil.HUANHANG;
            } else if (isConSpeChar(name)){
                errorMsg = errorMsg + sheetName + ConstantUtil.MESSAGE_DE_DI + i + "行,商品品類不能有特殊字符;" + ConstantUtil.HUANHANG;
            }

            // 校驗商品組別
            if (StringUtils.isEmpty(gname)) {
                errorMsg = errorMsg + sheetName + ConstantUtil.MESSAGE_DE_DI + i + "行,商品組別不能爲空;" + ConstantUtil.HUANHANG;
            } else if (gname.length() > 20) {
                errorMsg = errorMsg + sheetName + ConstantUtil.MESSAGE_DE_DI + i + "行,商品組別不能超過20位;" + ConstantUtil.HUANHANG;
            } else if (isConSpeChar(name)){
                errorMsg = errorMsg + sheetName + ConstantUtil.MESSAGE_DE_DI + i + "行,商品組別不能有特殊字符;" + ConstantUtil.HUANHANG;
            }

            // 校驗商品編碼
            if (StringUtils.isEmpty(productSn)) {
                errorMsg = errorMsg + sheetName + ConstantUtil.MESSAGE_DE_DI + i + "行,商品編碼不能爲空;" + ConstantUtil.HUANHANG;
            } else if (productSn.length() > 40) {
                errorMsg = errorMsg + sheetName + ConstantUtil.MESSAGE_DE_DI + i + "行,商品編碼不能超過40位;" + ConstantUtil.HUANHANG;
            }

            // 校驗海信編碼
            if (StringUtils.isEmpty(hisenseCoding)) {
                errorMsg = errorMsg + sheetName + ConstantUtil.MESSAGE_DE_DI + i + "行,海信編碼不能爲空;" + ConstantUtil.HUANHANG;
            } else if (hisenseCoding.length() > 8) {
                errorMsg = errorMsg + sheetName + ConstantUtil.MESSAGE_DE_DI + i + "行,海信編碼不能超過8位;" + ConstantUtil.HUANHANG;
            }

            // 校驗進貨價
            if (StringUtils.isEmpty(purchasePrice)) {
                errorMsg = errorMsg + sheetName + ConstantUtil.MESSAGE_DE_DI + i + "行,進貨價不能爲空;" + ConstantUtil.HUANHANG;
            } else if (!isNumber(purchasePrice)){
                errorMsg = errorMsg + sheetName + ConstantUtil.MESSAGE_DE_DI + i + "行,進貨價金額格式不對;" + ConstantUtil.HUANHANG;
            }

            // 校驗掛牌價
            if (StringUtils.isEmpty(price)) {
                errorMsg = errorMsg + sheetName + ConstantUtil.MESSAGE_DE_DI + i + "行,掛牌價不能爲空;" + ConstantUtil.HUANHANG;
            } else if (!isNumber(price)){
                errorMsg = errorMsg + sheetName + ConstantUtil.MESSAGE_DE_DI + i + "行,掛牌價金額格式不對;" + ConstantUtil.HUANHANG;
            }

            // 校驗稅收編碼
            if (StringUtils.isEmpty(codingTax)) {
                errorMsg = errorMsg + sheetName + ConstantUtil.MESSAGE_DE_DI + i + "行,稅收編碼不能爲空;" + ConstantUtil.HUANHANG;
            }

            // 校驗銷項稅
            if (StringUtils.isEmpty(taxOutput)) {
                errorMsg = errorMsg + sheetName + ConstantUtil.MESSAGE_DE_DI + i + "行,銷項稅不能爲空;" + ConstantUtil.HUANHANG;
            }

            // 校驗進項稅
            if (StringUtils.isEmpty(taxRate)) {
                errorMsg = errorMsg + sheetName + ConstantUtil.MESSAGE_DE_DI + i + "行,進項稅不能爲空;" + ConstantUtil.HUANHANG;
            }

            // 校驗包裝規格
            if (StringUtils.isEmpty(packingCoefficient)) {
                errorMsg = errorMsg + sheetName + ConstantUtil.MESSAGE_DE_DI + i + "行,包裝規格不能爲空;" + ConstantUtil.HUANHANG;
            }

            // 校驗商品屬性
            if (StringUtils.isEmpty(specs)) {
                errorMsg = errorMsg + sheetName + ConstantUtil.MESSAGE_DE_DI + i + "行,商品屬性不能爲空;" + ConstantUtil.HUANHANG;
            }

            // 校驗商品數量
            if (StringUtils.isEmpty(stock)) {
                errorMsg = errorMsg + sheetName + ConstantUtil.MESSAGE_DE_DI + i + "行,商品數量不能爲空;" + ConstantUtil.HUANHANG;
            }

            // 校驗計量單位
            if (StringUtils.isEmpty(unit)) {
                errorMsg = errorMsg + sheetName + ConstantUtil.MESSAGE_DE_DI + i + "行,計量單位不能爲空;" + ConstantUtil.HUANHANG;
            }

            // 校驗商品重量
            if (StringUtils.isEmpty(weight)) {
                errorMsg = errorMsg + sheetName + ConstantUtil.MESSAGE_DE_DI + i + "行,商品重量不能爲空;" + ConstantUtil.HUANHANG;
            }

            if (errorMsg.length() > 0) {
                removeList.add(rowMap);
            }
        }
        paramList.removeAll(removeList);
        // 判斷是否有錯誤消息 記錄 然後移除 剩下的數據 繼續導入
        if (errorMsg.length() > 0) {
            resMap.put(ConstantUtil.STATUS, ConstantUtil.STATUS_ZERO);
            String name = ConstantUtil.IMPORT_ERROR_MESSAGE;
            // 寫出錯誤消息
            creatTxtFile(name);
            writeTxtFile(errorMsg);
            resMap.put(ConstantUtil.MSG, errorMsg);
            resMap.put(ConstantUtil.FILEPATH, filenameTemp);
            resMap.put(ConstantUtil.COMMON_DATA, paramList);
            resMap.put(ConstantUtil.ERRORMSG, 1);
        } else {
            resMap.put(ConstantUtil.STATUS, ConstantUtil.STATUS_ZERO);
            resMap.put(ConstantUtil.MSG, ConstantUtil.IMPORTEXCEL_SUCCESS);
            resMap.put(ConstantUtil.COMMON_DATA, paramList);
        }

        return resMap;
    }

    //特殊驗證
    private static boolean isConSpeChar(String str) {
        String regEx = "[`~!@#$%^&*()+=|{}':;'\\[\\]<>/?~!@#¥%……&*——+|{}【】‘;:”“’。,、?]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return m.find();
    }

    //金額驗證
    public static boolean isNumber(String str){

        Matcher match=pattern.matcher(str);
        return match.find();
    }

    // 消息存儲路徑
    private static String filenameTemp;

    /**
     * 創建寫入文本
     *
     * @param name
     * @return
     * @throws IOException
     */
    public static boolean creatTxtFile(String name) throws IOException {

        File path = new File(ResourceUtils.getURL("classpath:").getPath());
        if (!path.exists()){
            path = new File("");
        }
        File upload = new File(path.getAbsolutePath() + ConstantUtil.STATIC_FRONTEND_PROJECT_TEMPLATE);
        if (!upload.exists()){
            upload.mkdirs();
        }
        boolean flag = false;
        filenameTemp = java.net.URLDecoder.decode(upload.getAbsolutePath().replaceAll("!", ConstantUtil.NULL_STRING), ConstantUtil.UTF_8) + File.separator + name + ConstantUtil.WORD_TXT;
        File filename = new File(filenameTemp);
        if (!filename.exists()) {
            filename.createNewFile();
            flag = true;
        }
        return flag;
    }


    public ResponseEntity<FileSystemResource> export(File file, String fileName) {
        if (file == null) {
            return null;
        }
        HttpHeaders headers = new HttpHeaders();
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Content-Disposition", "attachment; filename=" + fileName + ".txt");
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");
        return ResponseEntity
                .ok()
                .headers(headers)
                .contentLength(file.length())
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(new FileSystemResource(file));
    }

    /**
     * 向文本中寫入內容
     *
     * @param newStr
     * @return
     * @throws IOException
     */
    public static boolean writeTxtFile(String newStr) throws IOException {
        // 先讀取原有文件內容,然後進行寫入操作
        boolean flag = false;
        String filein = newStr + ConstantUtil.HUANHANG;

        FileInputStream fis = null;
        InputStreamReader isr = null;
        BufferedReader br = null;

        FileOutputStream fos = null;
        PrintWriter pw = null;
        try {
            // 文件路徑
            File file = new File(filenameTemp);
            // 將文件讀入輸入流
            fis = new FileInputStream(file);
            isr = new InputStreamReader(fis);
            br = new BufferedReader(isr);
            StringBuffer buf = new StringBuffer();

            buf.append(filein);

            fos = new FileOutputStream(file);
            pw = new PrintWriter(fos);
            pw.write(buf.toString().toCharArray());
            pw.flush();
            flag = true;
        } catch (IOException e1) {
            throw e1;
        } finally {
            if (pw != null) {
                pw.close();
            }
            if (fos != null) {
                fos.close();
            }
            if (br != null) {
                br.close();
            }
            if (isr != null) {
                isr.close();
            }
            if (fis != null) {
                fis.close();
            }
        }
        return flag;
    }

}

文件導入工具類ConstantUtil 類

package com.macro.mall.util;


import java.util.HashMap;
import java.util.Map;

/**
 * 文件名 ConstantUtil 描述 EXecl常量工具類
 * @date 2019年12月1日17:14:44
 * @author gbl
 */
public class ConstantUtil {

    /**
     * 總數常量KEY
     */
    public static final String TOTAL = "total";

    /**
     * 數據常量KEY
     */
    public static final String ROWS = "rows";

    /**
     * 消息KEY常量
     */
    public static final String MSG = "errorMsg";

    /**
     * 消息狀態KEY常量
     */
    public static final String STATUS = "errorCode";

    /**
     * sheetName字符串常量
     */
    public static final String SHEETNAME = "sheetName";

    /**
     * 常量字符串0
     */
    public static final String STATUS_ZERO = "0";

    /**
     * 常量字符串1
     */
    public static final String STATUS_ONE = "1";

    /**
     * 常量字符串1
     */
    public static final String ERROR_MSG = "1";


    /**
     * 常量字符串-1
     */
    public static final String STATUS_FUONE = "-1";

    /**
     * 常量整型0
     */
    public static final int COMMONS_ZERO = 0;

    /**
     * 常量整型1
     */
    public static final int COMMONS_ONE = 1;

    /**
     * 操作成功
     */
    public static final String COMMON_SUCCESS = "操作成功";

    /**
     * 操作失敗
     */
    public static final String COMMON_FAILURE = "操作失敗";

    /**
     * 品類名稱不存在
     */
    public static final String COMMON_VNAME = "品類名稱不存在";

    /**
     * 組別名稱不存在
     */
    public static final String COMMON_GNAME = "組別名稱不存在";

    /**
     * 未知原因導致的失敗提示消息常量
     */
    public static final String COMMON_WZYY_FAILURE = "由於未知原因導致操作失敗,請聯繫管理員。";

    /**
     * 模版名稱字符串常量
     */
    public static final String MBMC_KEY = "mbmc";

    /**
     * 模版編號字符串常量
     */
    public static final String MBBH_KEY = "mbbh";

    /**
     * "模版名稱存在,請更換"字符串常量
     */
    public static final String MBMC_STRING_HAVE = "模版名稱存在,請更換";

    /**
     * "模版編號存在,請更換"字符串常量
     */
    public static final String MBBH_STRING_HAVE = "模版編號存在,請更換";

    /**
     * tag字符串常量
     */
    public static final String TAG_KEY = "tag";

    /**
     * dataList字符串常量
     */
    public static final String DATALIST_KEY = "dataList";

    /**
     * 上傳文件失敗字符串常量
     */
    public static final String COMMON_UPLOAD_FAILE = "上傳文件失敗";

    /**
     * 上傳文件成功字符串常量
     */
    public static final String COMMON_UPLOAD_SUCCESS = "上傳文件成功";

    /**
     * "text"字符串常量
     */
    public static final String TEXT_KEY = "text";

    /**
     * 文本分區類型: 0
     */
    public static final String FQLX_TXT_ZERO = "0";

    /**
     * 文本分區類型: 1
     */
    public static final String FQLX_IMG_ONE = "1";

    /**
     * 文本分區類型: 2
     */
    public static final String FQLX_VOID_TWO = "2";

    /**
     * 是否使用全部的標誌tag
     */
    public static final String COMMON_TAG = "tag";

    /**
     * 全部的常量
     */
    public static final String COMMON_QUANBU = "全部";

    /**
     * 線路ID常量
     */
    public static final String COMMON_XLID = "xlid";

    /**
     * 線路名稱常量
     */
    public static final String COMMON_XLMC = "xlmc";

    /**
     * 線路名稱常量
     */
    public static final String COMMON_LPMC = "lpmc";

    /**
     * 空串常量
     */
    public static final String NULL_STRING = "";

    /**
     * led方向
     */
    public static final String LEDFX_VALUE = "15";

    /**
     * 方向
     */
    public static final String FX_VALUE = "16";

    /**
     * 屬性類型對應字段編號
     */
    public static final Map<String, Object> LED_ATTR_COMMONSET_MAP = new HashMap<>();

    static {
        LED_ATTR_COMMONSET_MAP.put("font-size", "5");
        LED_ATTR_COMMONSET_MAP.put("font-style", "6");
        LED_ATTR_COMMONSET_MAP.put("font-weight", "7");
        LED_ATTR_COMMONSET_MAP.put("show-style", "8");
        LED_ATTR_COMMONSET_MAP.put("move-speed", "9");
        LED_ATTR_COMMONSET_MAP.put("sound-flag", "10");
        LED_ATTR_COMMONSET_MAP.put("sound-volume", "11");
        LED_ATTR_COMMONSET_MAP.put("sound-speed", "12");
        LED_ATTR_COMMONSET_MAP.put("sound-count", "13");
        LED_ATTR_COMMONSET_MAP.put("replay-count", "14");

    }

    /**
     * JcsjService字符串常量
     */
    public static final String JCSJSERVICE_KEY = "JcsjService";

    /**
     * 用戶名常量
     */
    public static final String COMMON_USER_NAME = "userName";

    /**
     * dataList字符串常量KEY
     */
    public static final String DATALIST = "dataList";

    /**
     * 導入數據集合KEY常量
     */
    public static final String IMPORTLIST = "importData";

    /**
     * 數據key常量
     */
    public static final String COMMON_DATA = "data";

    /**
     * 導入Excel文件列標題變量名
     */
    public static final String ANY_CONSTANT_IMPORT_TITLEVAR = "virtualGoods,barCode,name,vname,gname,productSn,hisenseCoding,purchasePrice,price,codingTax," +
            "taxOutput,taxRate,packingCoefficient,specs,stock,unit,weight";

    /**
     * 導入Excel文件中數據起始行, 從0開始
     */
    public static final int ANY_CONSTANT_IMPORT_DATAROW = 1;

    /**
     * 導入Excel文件中數據總列數
     */
    public static final int ANY_CONSTANT_IMPORT_COUNTCOL = 17;


    /**
     * 導入Excel文件列標題
     */
    public static final String ANY_CONSTANT_IMPORT_TITLE = "商品類型(實物0/虛擬1),商品條碼,商品名稱,商品品類,商品組別,商品編碼,海信編碼,進貨價,掛牌價,稅收編碼" +
            ",銷項稅(%),進項稅(%),包裝規格,商品屬性,商品數量,計量單位,商品重量(克)";

    /**
     * 導入成功提示消息
     */
    public static final String IMPORTEXCEL_SUCCESS = "導入成功";

    /**
     * 導入異常提示消息
     */
    public static final String IMPORTEXCEL_FAILE = "導入異常";

    /**
     * Excel的表頭不能爲空,請使用標準模版。
     */
    public static final String IMPORTEXCEL_TITLE_NULL = "Excel的表頭不能爲空,請使用標準模版。";

    /**
     * Excel的表頭不能爲空,請使用標準模版。
     */
    public static final String IMPORTEXCEL_TITLE_ERROR = "Excel的表頭不正確,請使用標準模版。";

    /**
     * 導入電子站牌訪問請求接口常量
     */
    public static final String IMPORTLEDEXCEL = "/importLedExcel";

    /**
     * 導入電子站牌參數常量
     */
    public static final String FILE = "file";

    /**
     * 逗號常量
     */
    public static final String DOUHAO = ",";

    /**
     * errorMsg字符串常量
     */
    public static final String ERRORMSG = "errorMsg";

    /**
     * titleString字符串常量
     */
    public static final String TITLESTRING = "titleString";

    /**
     * IP正則表達式字符串常量
     */
    public static final String IPREG = "^((25[0-5]|2[0-4]\\d|((1\\d{2})|([1-9]?\\d)))\\.){3}(25[0-5]|2[0-4]\\d|((1\\d{2})|([1-9]?\\d)))$";

    /**
     * sheet頁名稱不能爲空,請按照'線路名(運行方向)'的格式進行添加。例如:'801(上行)'常量
     */
    public static final String SHEETNAME_CANNOT_NULL = "sheet頁名稱不能爲空,請按照'線路名(運行方向)'的格式進行添加。例如:'801(上行)'";

    /**
     * sheet頁名稱長度不符合規範,請保證sheet頁名稱長度在5-54之間'常量
     */
    public static final String SHEETNAME_LENGTH_ERROR = "sheet頁名稱長度不符合規範,請保證sheet頁名稱長度在5-54之間'";

    /**
     * sheet頁獲取的線路名稱常量
     */
    public static final String SHEETXLMC = "sheetXlmc";

    /**
     * 上行常量
     */
    public static final String SHANGXING = "上行";

    /**
     * sheet頁獲取的運行方向常量
     */
    public static final String SHEETYXFX = "sheetYxfx";

    /**
     * sheet頁獲取的運行方向編碼常量
     */
    public static final String SHEETYXFXSTATUS = "sheetYxfxStatus";

    /**
     * sheet頁獲取的運行方向上行編碼值常量
     */
    public static final String SHEETYXFX_SHANGXING = "0";

    /**
     * 下行常量
     */
    public static final String XIAXIGN = "下行";

    /**
     * sheet頁獲取的運行方向下行編碼值常量
     */
    public static final String SHEETYXFX_XIAXING = "1";

    /**
     * 導入錯誤消息文本字符串常量
     */
    public static final String IMPORT_ERROR_MESSAGE = "cwxx";

    /**
     * "filePath"字符串常量
     */
    public static final String FILEPATH = "filePath";

    /**
     * 的第字符串常量
     */
    public static final String MESSAGE_DE_DI = "的第";

    /**
     * 換行標記
     */
    public static final String HUANHANG = "\r\n";

    /**
     * 錯誤消息存儲路徑常量
     */
    public static final String STATIC_FRONTEND_PROJECT_TEMPLATE = "/static/excel/";

    /**
     * UTF_8字符串常量
     */
    public static final String UTF_8 = "UTF-8";

    /**
     * .txt字符串常量
     */
    public static final String WORD_TXT = ".txt";


    /**
     * user-agent字符串常量
     */
    public static final String USER_AGENT = "user-agent";

    /**
     * msie字符串常量
     */
    public static final String MSIE = "msie";

    /**
     * 錯誤信息
     */
    public static final String ERRORFILENAME = "錯誤信息";

    /**
     * like gecko字符串常量
     */
    public static final String LIKE_GECKO = "like gecko";

    /**
     * ISO_8859_1字符串常量
     */
    public static final String ISO_8859_1 = "iso-8859-1";
}

文件導入工具類 ExcelUtils  類

package com.macro.mall.util;

import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;

/**
 * @author djg
 * @date 2019/7/24 16:24
 * @des 導出excel模板
 */
public class ExcelUtils {
    public static void exportExcelUsers(HttpServletResponse response, String[] handers, String excleName) throws Exception {
        try {
            HSSFWorkbook wb = new HSSFWorkbook();
            HSSFSheet sheet = wb.createSheet("sheet1");
            HSSFCellStyle style = disFont(wb);
            HSSFRow rowFirst = sheet.createRow(0);
            rowFirst.setHeight((short) 300);
            // 設置列寬
            for (int i = 0; i < handers.length; i++) {
                sheet.setColumnWidth((short) i, (short) 8300);
            }
            for (int i = 0; i < handers.length; i++) {
                HSSFCell cell = rowFirst.createCell(i);
                cell.setCellStyle(style);
                cell.setCellValue(handers[i]);
            }
            //寫出文件(path爲文件路徑含文件名)
            OutputStream output = response.getOutputStream();
            response.reset();
            response.setHeader("Content-disposition", "attachment; filename=" + excleName + ".xls");
            response.setContentType("application/msexcel");
            wb.write(output);
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    public static HSSFCellStyle disFont(HSSFWorkbook wb) {
        HSSFCellStyle style = wb.createCellStyle();
        style.setBorderBottom(BorderStyle.THIN);//下邊框
        style.setBorderLeft(BorderStyle.THIN);//左邊框
        style.setBorderRight(BorderStyle.THIN);//右邊框
        style.setBorderTop(BorderStyle.THIN); //上邊框
        style.setAlignment(HorizontalAlignment.CENTER);//水平居中
        style.setVerticalAlignment(VerticalAlignment.CENTER);//垂直居中
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        style.setFillForegroundColor(IndexedColors.WHITE.index);
        HSSFFont font = wb.createFont();
//        font.setFontName("華文行楷");//設置字體名稱
        font.setFontHeightInPoints((short) 10);//設置字號
        font.setItalic(false);//設置是否爲斜體
        font.setBold(true);//設置是否加粗
        style.setFont(font);
        return style;
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章