EasyExcel导入,导出工具类

service层

package com.example.demo.service.impl;

import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.example.demo.config.ImportException;
import com.example.demo.model.entity.User;
import com.example.demo.response.BaseResponse;
import com.example.demo.service.IUserService;
import com.example.demo.service.ImportService;
import com.example.demo.utils.ExcelUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class ImportServiceImpl implements ImportService {

    /**
     * 每隔2条存储数据库,实际使用中可以3000条,然后清理list ,方便内存回收
     */
    private static final int BATCH_COUNT = 2;

    @Resource
    private IUserService userService;


    @Transactional
    @Override
    public BaseResponse importExcel(MultipartFile file) {
        List<User> dataList = null;
        ExcelTypeEnum excelType = ExcelTypeEnum.CSV;
        // 导入
        try {
            dataList = ExcelUtils.importExcel(file, User.class, excelType);
        } catch (IOException e) {
            log.info("导入失败!");
        }

        log.info("{}条数据,开始存储数据库!", dataList.size());
        // 使用mybatis plus 的批量新增方法
        userService.saveBatch(dataList, BATCH_COUNT);
        log.info("存储数据库成功!");
        // 返回格式作拼接
        BaseResponse response = new BaseResponse();
        response.setData(dataList);
        response.setCode("200");
        response.setMessage("导入成功");
        return response;
    }

    @Override
    public void exportExcel(HttpServletResponse response) {
        List<User> list = new ArrayList<>();
        User user = new User();
        user.setUid("11");
        user.setUserName("测试11");
        user.setPassword("测试11");
        list.add(user);
        User user1 = new User();
        user1.setUid("12");
        user1.setUserName("测试12");
        user1.setPassword("测试12");
        list.add(user1);
        String sheetName = "sheet1";
        String fileName = "csv文件导出";
        // 文件格式 .xls/.xlsx/.csv
        ExcelTypeEnum excelType = ExcelTypeEnum.CSV;
        try {
            ExcelUtils.exportExcel(response, list, sheetName, fileName, excelType);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    public void downloadExcel(HttpServletResponse response) {
        //获取本地文件的路径
        String filePath = "D:\\个人资料\\test.xlsx";
        try {
            ExcelUtils.downloadExcel(filePath, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

ExcelUtils

package com.example.demo.utils;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.example.demo.config.ImportException;
import com.example.demo.config.ReadListener;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.List;

@Slf4j
public class ExcelUtils {

    private static final String DEFAULT_EXCEL_TYPE = ".xlsx";
    private static final Charset CHARSET_UTF8 = Charset.forName("UTF-8");


    public static<T> List<T> importExcel(MultipartFile file, Class<T> clazz, ExcelTypeEnum excelType) throws IOException {
        // 判断文件是否为空
        if (file.isEmpty() || file.getSize() <= 0) {
            log.error("上传文件大小为空");
        }
        // 获取文件名
        String originalFilename = file.getOriginalFilename();
        // 文件格式作校验
        if (!StringUtils.endsWithIgnoreCase(originalFilename, "xlsx")
                && !StringUtils.endsWithIgnoreCase(originalFilename, "xls")
                && !StringUtils.endsWithIgnoreCase(originalFilename, "csv")) {
            log.error("文件格式错误");
        }

        List<T> dataList = null;
        try (InputStream inputStream = file.getInputStream()) {
            dataList = EasyExcel.read(inputStream, clazz, new ReadListener()).excelType(excelType).sheet().doReadSync();
        } catch (Exception e) {
            log.error("导入文件失败:{}", e.getMessage(), e);
            throw new ImportException("导入文件失败", e.getMessage());
        }
        return dataList;
    }

    /**
     * 根据文件路径下载模板文件
     * @param response
     */
    public static void downloadExcel(String filePath, HttpServletResponse response) {
        //获取要下载的模板名称
        String fileName = getFileNameFromPath(filePath);
        // 使用try-with-resources语句,以确保资源得到正确关闭
        try (FileInputStream input = new FileInputStream(filePath);
             // 使用缓冲区减少IO操作次数:可以使用缓冲区来减少IO操作次数,提高下载速度
             BufferedInputStream bis = new BufferedInputStream(input);
             OutputStream out = response.getOutputStream();
             BufferedOutputStream bos = new BufferedOutputStream(out)) {
            fileName = URLEncoder.encode(fileName, CHARSET_UTF8.name());
            setResponseHeader(response, fileName);
            byte[] buffer = new byte[2048];
            int len;
            while ((len = bis.read(buffer)) != -1) {
                bos.write(buffer, 0, len);
            }
        } catch (Exception ex) {
            log.error("下载文件失败:{}", ex.getMessage());
            ex.printStackTrace();
        }
    }

    /**
     * EasyExcel导出
     * @param response
     * @param list
     * @param sheetName
     * @param fileName
     */
    public static <T> void exportExcel(HttpServletResponse response, List<T> list, String sheetName, String fileName, ExcelTypeEnum excelType) throws IOException {
        fileName = fileName + (excelType != null ? excelType.getValue() : DEFAULT_EXCEL_TYPE);
        fileName = URLEncoder.encode(fileName, CHARSET_UTF8.name());
        try (OutputStream outputStream = response.getOutputStream()) {
            setResponseHeader(response, fileName);
            Class<T> clazz = (Class<T>) list.get(0).getClass();
            EasyExcel.write(outputStream, clazz)
                    .excelType(excelType != null ? excelType : ExcelTypeEnum.XLSX)
                    .sheet(sheetName)
                    .doWrite(list);
        } catch (Exception e) {
            e.printStackTrace();
            throw new IOException("导出Excel文件失败", e);
        }
    }

    /**
     * 将文件名编码和设置响应头的代码提取成公共方法,以提高代码的可复用性和可读性
     * @param response
     * @param fileName
     * @throws UnsupportedEncodingException
     */
    public static void setResponseHeader(HttpServletResponse response, String fileName) throws UnsupportedEncodingException {
        response.setContentType("application/msexcel");//
        response.setCharacterEncoding(CHARSET_UTF8.name());
        response.addHeader("Content-Disposition","attachment;filename=" + new String(fileName.getBytes(CHARSET_UTF8.name()),"ISO8859-1") + "");
    }

    public static String getFileNameFromPath(String filePath) {
        return new File(filePath.trim()).getName();
    }
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值