SpringBoot——excel导入导出

集成依赖:

   
        
            net.sourceforge.jexcelapi
            jxl
            2.6.12
        

excel导出请求方法:

后端接收方法:

   /**
     * 导出excel
     * @return
     */
    @ResponseBody
    @PostMapping("/excelExport")
    public Result excelExport() {
        String[] ids = request.getParameterValues("ids[]");
        List list = new ArrayList<>();
        for(int i=0;i

前端请求方法(这里使用的layui框架):

 //导出excel
        window.excelExport=function(){
            var checkStatus = table.checkStatus('YD-order-orderManage-list')
                    , checkData = checkStatus.data //得到选中的数据
                    , ids = [];
            if (checkData.length === 0) {
                return layer.msg('请选择数据');
            } else {
                for (var i in checkData) {
                    ids.push(checkData[i].id);
                }
            }
            layer.confirm('确定导出吗?', function (index) {
                //执行 Ajax 后重载
                admin.req({
                    type: 'post',
                    url: '${ctx}/order/orderManage/excelExport',
                    data: {
                        'ids': ids
                    },
                    done: function (res) {
                        // 登入成功的提示与跳转
                        if (res.code === 0) {
                            table.reload('YD-order-orderManage-list');
                            window.open(res.data)
                            layer.msg('已导出');
                        } else {
                            layer.msg(res.msg);
                        }
                    }
                });
            });

        }

excel导入请求方法:

后端接收方法:

/**
     * 导入excel
     * @return
     */
    @ResponseBody
    @PostMapping("/excelEntrance")
    public Result excelEntrance(@RequestParam MultipartFile file) {
        //获取上传文件名,包含后缀uploadOneFile
        String originalFilename = file.getOriginalFilename();
        //获取后缀
        String substring = originalFilename.substring(originalFilename.lastIndexOf(".")+1);
        log.info("后缀:{}",substring);
        if(substring.equals("xls")||substring.equals("xlsx")){
            String img = "";
            try {
                // 上传文件
                img = ImageUtils.uploadOneFile(file
                        , AttachmentPathEnum.getPathById(99)
                        , true);
            } catch (Exception e) {
                throw new WebJsonException(e, ReturnCodeEnum.UNKNOWN_ERR);
            }
            log.info("图片路径:{}",img);
            log.info("完整路径:{}",pathUrl+img);
            List list = ExcelUtil.excelImport(pathUrl+img);
            list.stream().filter((e)->!e.getTrackNumber().equals(""))
                    .forEach(e->{
                        Order order=orderService.getOne(new QueryWrapper().lambda()
                                .eq(Order::getShopOrderCode, e.getShopOrderCode().replace(" ", "")));
                        if(order!=null){
                            if(order.getTradeStatus().equals(OrderEnum.STAY_SHIPMENTS.getCode())){//订单状态必须为待发货
                                order.setTrackNumber(e.getTrackNumber().replace(" ", ""));
                                order.setTradeStatus(OrderEnum.STAY_RECEIVING.getCode());
                                orderService.updateById(order);
                            }
                        }
                    });
            ExcelUtil.deleteFile(pathUrl+img);
            return new Result(ReturnCodeEnum.SUCCESS);
        }
        return new Result(ReturnCodeEnum.ORDER_EXCEL_UPLOAD_ERR);
    }

前端请求方法(前端用了layui框架):

  //导入excel
        window.excelEntrance=function(){
            var index = layer.open({
                type: 1
                ,title: '导入excel'
                ,content: '
' ,area: ['300px', '200px'] ,maxmin: false ,btn: ['确定', '取消'] ,yes: function(index, layero){ var formData=new FormData($("#uploadForm")[0]); $.ajax({ type : "POST", url : '${ctx}/order/orderManage/excelEntrance', data : formData, async: false, cache: false, contentType: false, processData: false, success : function(res) { if(res.code==0){ layer.msg('操作成功!'); //点击确认触发 iframe 内容中的按钮提交 layer.close(index) }else { layer.msg(res.msg); } } }); } }); }

导入excel上传文件工具类:

package com.yd.mall.common.utils;

import com.yd.mall.common.enums.GoodsImgSizeEnum;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.activation.MimetypesFileTypeMap;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import java.util.UUID;

/**
 * @Description 图片上传工具类
 * @Author pengar
 * @Date 2018-08-28 14:05
 * @Version 1.0
 */
public class ImageUtils {

    private static MimetypesFileTypeMap mtftp;

    private static Properties props;

    static{
        try(InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("upload.properties")) {
            props = new Properties();
            props.load(in);
            mtftp = new MimetypesFileTypeMap();
            mtftp.addMimeTypes(getMimeTypes());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 将数据库图片资源路径转换成网页url
     * @param path
     * @return
     * @throws Exception
     */
    public static String convertDbUrl2WebUrl(String path){
        if(StringUtils.isBlank(path)){
            return getServerURL()+getDefaultImgPath();
        }
        if(path.indexOf("http://")==-1 || path.indexOf("https://")==-1){
            path=getServerURL()+path;
        }
        return path;
    }

    /**
     * 将网页url路径转换成数据库图片资源
     * @param path
     * @return
     * @throws Exception
     */
    public static String convertWebUrl2DbUrl(String path){
        if(StringUtils.isBlank(path)){
            return "";
        }
        if(path.indexOf("http://")==0 || path.indexOf("https://")==0){
            path=path.replaceAll(getServerURL(), "");
        }
        return path;
    }

    /**
     * 切换成各种尺寸的图片
     * @param url
     * @param gis
     * @param returnDB
     * @return
     */
    public static String convert2SizeUrl(String url, GoodsImgSizeEnum gis, boolean returnDB){
        if(url.indexOf("http://")==0 || url.indexOf("https://")==0){
            url = convertDbUrl2WebUrl(url);
        }

        int index = url.lastIndexOf(".");
        String suffix = url.substring(index);
        url=url.substring(0, index) + gis.getSuffix()  + suffix;
        if(returnDB)
            url = convertWebUrl2DbUrl(url);
        return url;
    }

    /**
     * 获取默认图片地址
     * @return
     */
    private static String getDefaultImgPath() {
        String path = props.getProperty("img.default.Path");
        if(StringUtils.isBlank(path)){
            return "";
        }
        return path;
    }

    /**
     * 获取文件类型
     * @param filePath
     * @return
     * @throws Exception
     */
    public static String getSuffix(String filePath) throws Exception{
        File img = new File(filePath);
        String suffix="";
        if(img.isFile()){
            int i = img.getPath().lastIndexOf(".");
            if(i!=-1){
                suffix = img.getPath().substring(i);
            }else{
                suffix = ".jpg";
            }
        }
        return suffix;
    }

    /**
     * 处理不同系统的上传路径
     * @param path
     * @return
     */
    public static String dealOsPath(String path){
        String os = System.getProperty("os.name");
        if(os.toLowerCase().startsWith("win")){
            if(path.startsWith(getServerURL())){
                path = path.replaceFirst(getServerURL(), getUploadPath());
            }else{
                path = getUploadPath()+path;
            }
        }else{
            path= getUploadPath()+path;
        }
        return path;
    }

    /**
     * 删除原图
     * @param path
     * @return
     * @throws Exception
     */
    public static int delLocalImg(String path) throws Exception{
        path = dealOsPath(path);
        File file = new File(path);
        file.delete();
        return 0;
    }

    /**
     * 判断是否为指定图片类型
     * @param file
     * @return
     */
    public static void isImage(File file){
        String mimetype= mtftp.getContentType(file);
        String type = mimetype.split("/")[0];
        if(!type.equals("image")){
            throw new RuntimeException("请上传正确的图片类型");
        }
    }

    /**
     * 获取图片服务器的路径
     * @return
     */
    public static String getServerURL(){
        return props.getProperty("img.server.URL");
    }

    /**
     * 获取随机文件名
     * @return
     * @throws Exception
     */
    public static String getRamdomName(){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd-");
        String format = sdf.format(new Date());
        format+=UUID.randomUUID();
        return format;
    }

    /**
     * 获取图片上传的根目录
     * @return
     */
    public static String getUploadPath(){
        return props.getProperty("img.upload.Path");
    }

    /**
     * 获取定义为图片的文件类型
     * @return
     */
    public static String getMimeTypes(){
        return props.getProperty("img.file.types");
    }

    /**
     * 上传图片
     * @param mFile 文件
     * @param targetDir 上传路径
     * @return
     */
    public static String upload(MultipartFile mFile, String targetDir) {
       return upload(mFile, targetDir, false);
    }

   
    //上传单个文件
    public static String uploadOneFile(MultipartFile mFile, String targetDir, boolean isGoods) {
        String dbPath = "";
        try {
            //获取上传文件名,包含后缀uploadOneFile
            String originalFilename = mFile.getOriginalFilename();
            String fileName = mFile.getOriginalFilename();
            dbPath=targetDir+"/"+ fileName;
            //获取后缀
            String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
            // 实体路径
            targetDir = dealOsPath(targetDir);
            File dir = new File(targetDir);
            if(!dir.isDirectory()){
                dir.mkdirs();
            }
            File uploadFile  = new File(targetDir,fileName);
            //将上传文件保存到路径
            try {
                mFile.transferTo(uploadFile);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dbPath;
    }
}

excel核心工具类(主要就是这个工具类):

package com.yd.mall.admin.common.utils;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.function.Predicate;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 

* excel工具类 *

* * @author: Mr.xiang * @date: 2019-04-22 10:45 **/ public class ExcelUtil { /** * 导出excel * @param list * @param path */ public static void excelExport(List list, String path) { WritableWorkbook book = null; try { // 创建一个Excel文件对象 book = Workbook.createWorkbook(new File(path)); // 创建Excel第一个选项卡对象 WritableSheet sheet = book.createSheet("第一页", 0); // 设置表头,第一行内容 // Label参数说明:第一个是列,第二个是行,第三个是要写入的数据值,索引值都是从0开始 Label label1 = new Label(0, 0, "订单号");// 对应为第1列第1行的数据 Label label2 = new Label(1, 0, "发货单号");// 对应为第2列第1行的数据 // 添加单元格到选项卡中 sheet.addCell(label1); sheet.addCell(label2); // 遍历集合并添加数据到行,每行对应一个对象 for (int i = 0; i < list.size(); i++) { Customer customer = list.get(i); // 表头占据第一行,所以下面行数是索引值+1 // 跟上面添加表头一样添加单元格数据,这里为了方便直接使用链式编程 sheet.addCell(new Label(0, i + 1, customer.getShopOrderCode())); sheet.addCell(new Label(1, i + 1, customer.getTrackNumber())); } // 写入数据到目标文件 book.write(); } catch (Exception e) { e.printStackTrace(); } finally { try { // 关闭 book.close(); } catch (Exception e) { e.printStackTrace(); } } } /** * 导入excel * @param path * @return */ public static List excelImport(String path) { List list = new ArrayList<>(); Workbook book = null; try { // 获取Excel对象 book = book.getWorkbook(new File(path)); // 获取Excel第一个选项卡对象 Sheet sheet = book.getSheet(0); // 遍历选项卡,第一行是表头,所以索引数-1 for (int i = 0; i < sheet.getRows() - 1; i++) { Customer customer = new Customer(); // 获取第一列第二行单元格对象 Cell cell = sheet.getCell(0, i + 1); customer.setShopOrderCode(cell.getContents()); // 获取第二行其他数据 customer.setTrackNumber(sheet.getCell(1, i + 1).getContents()); list.add(customer); } // 返回导入的数据集合 return list; } catch (Exception e) { e.printStackTrace(); } finally { try { // 关闭 book.close(); } catch (Exception e) { e.printStackTrace(); } } return null; } // public static void main(String[] args) { // // // 创建数据 // for (int i = 0; i <10; i++) { // Customer customer = new Customer(); // customer.setShopOrderCode("隔壁老王_" + i); // customer.setTrackNumber("就是那么6"); // list.add(customer); // } // String path = "D:\\eclelTest\\xs.xls"; // if (!(new File(path)).getParentFile().exists()) {//判断该路径是否存在如果不存在就创建一个 // (new File(path)).getParentFile().mkdirs(); // } // System.out.println("开始导出..."); // long s1 = new Date().getTime(); // // 开始导出 // excelExport(list, path); // long s2 = new Date().getTime(); // long time = s2 - s1; // System.out.println("导出完成!消耗时间:" + time + "毫秒"); // } public static void main(String[] args) { String path = "D:\\eclelTest\\xs.xls"; List list = excelImport(path); list.stream().filter((e)->e.getTrackNumber().equals("")).forEach(System.out::println); deleteFile(path); } /** * 删除单个文件 * * @param fileName * 要删除的文件的文件名 * @return 单个文件删除成功返回true,否则返回false */ public static boolean deleteFile(String fileName) { File file = new File(fileName); // 如果文件路径所对应的文件存在,并且是一个文件,则直接删除 if (file.exists() && file.isFile()) { if (file.delete()) { System.out.println("删除单个文件" + fileName + "成功!"); return true; } else { System.out.println("删除单个文件" + fileName + "失败!"); return false; } } else { System.out.println("删除单个文件失败:" + fileName + "不存在!"); return false; } } }

好了就到这里了,如果有帮到你就点个赞吧

你可能感兴趣的:(SpringBoot——excel导入导出)