easypoi 实现excel导入导出(创建文件目录+导出压缩+附件下载)

easypoi 实现excel导入导出

  • 1. pom文件引入maven依赖
  • 2. 创建导入导出工具类ExcelUtils,ExcelExportStylerUtil
  • 3.导入模板下载
  • 4.导入示例
  • 5.导出示例

1. pom文件引入maven依赖

 <!--导入导出的工具包,可以完成Excel导出,导入,Word的导出,Excel的导出功能-->
 <dependency>
     <groupId>cn.afterturn</groupId>
     <artifactId>easypoi-base</artifactId>
     <version>4.1.0</version>
 </dependency>
 <!--耦合了spring-mvc 基于AbstractView,极大的简化spring-mvc下的导出功能-->
 <dependency>
     <groupId>cn.afterturn</groupId>
     <artifactId>easypoi-web</artifactId>
     <version>4.1.0</version>
 </dependency>
 <!--基础注解包,作用与实体对象上,拆分后方便maven多工程的依赖管理-->
 <dependency>
     <groupId>cn.afterturn</groupId>
     <artifactId>easypoi-annotation</artifactId>
     <version>4.1.0</version>
 </dependency>

2. 创建导入导出工具类ExcelUtils,ExcelExportStylerUtil

package org.jeecg.utils.excel;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.hutool.core.collection.CollectionUtil;
import com.sun.xml.internal.messaging.saaj.util.ByteOutputStream;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.jeecg.common.util.MinioUtil;
import org.jeecg.entity.Attachment;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 类说明
 *
 * @author chengyan
 * @date 2023/3/27
 */
@Slf4j
@Component
public class ExcelUtils {

    @Value("${jeecg.minio.bucketName}")
    private String bucketName;
    @Value("${jeecg.minio.minio_url}")
    private String minioUrl;

    /**
     * 多个Excel表压入压缩包导出
     */
    /**
     * 创建Excel表的工作簿Workbook
     * @param list 数据集合
     * @param title 标题
     * @param sheetName 页名
     * @param entity 实体类
     * @return
     */
    public static Workbook Excel(List<?> list, String title, String sheetName, Class<?> entity) {
        ExportParams exportParams = new ExportParams(title, sheetName);
        //添加样式
        exportParams.setStyle(ExcelExportStylerUtil.class);
        //冻结表头
        exportParams.setCreateHeadRows(true);
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, entity, list);
        return workbook;
    }

    /**
     * 工作簿集合导出压缩包
     * @param response
     * @param workbooks  工作簿集合
     * @param fileName   压缩包名
     * @param exelNames  excel表名
     * @param parentName 多级目录名
     */
    public  void exportZip(HttpServletResponse response, List<Workbook> workbooks, String fileName, List<String> exelNames, List<String> parentName,Map<String,List<Attachment>> attachmentGroup){
        try {
            // 指定下载的文件名--设置响应头
            response.setContentType("application/zip; charset=UTF-8");
            response.setDateHeader("Expires", 0);
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8") + ".zip");
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setCharacterEncoding("UTF-8");

            // 多个Excel写入压缩文件
            ZipOutputStream zipOutputStream = new ZipOutputStream(response.getOutputStream());
            for (int i = 0; i < workbooks.size(); i++) {
                ZipEntry entry =null;
                if (CollectionUtil.isEmpty(parentName)) {
                    //若想在zip包生成,一级目录\二级目录\excel表名.xlsx文件
                    //new ZipEntry("一级目录\二级目录\excel表名.xlsx");
                    entry = new ZipEntry(exelNames.get(i)+".xlsx");
                }else {
                    entry = new ZipEntry(parentName.get(i)+"\\"+exelNames.get(i)+""+".xlsx");
                }
                zipOutputStream.putNextEntry(entry);
                ByteOutputStream byteOutputStream = new ByteOutputStream();
                workbooks.get(i).write(byteOutputStream);
                byteOutputStream.writeTo(zipOutputStream);
                byteOutputStream.close();
                // 写出附件信息
                if(!ObjectUtils.isEmpty(attachmentGroup)){
                    List<Attachment> attachments = attachmentGroup.get(parentName.get(i));
                    if (attachments != null && attachments.size() > 0){
                        for (Attachment attachment : attachments) {
                            File file = new File(attachment.getFileUrl());
                            String name = file.getName();
                            String url=attachment.getFileUrl();
                            String chartStr=minioUrl+"/"+bucketName;
                            String objectName=url.substring(attachment.getFileUrl().indexOf(chartStr)+chartStr.length());
                            InputStream inputStream = MinioUtil.getMinioFile(bucketName, objectName);
                            if(ObjectUtils.isEmpty(inputStream)){
                                log.info("导出-附件信息未找到,minio objectName:{}",objectName);
                                log.info("导出-附件信息未找到,附件地址:{}",attachment.getFileUrl());
                            }else{
                                String mineFile = parentName.get(i)+"\\" +"附件" +"\\"+name;
                                entry = new ZipEntry(mineFile);
                                zipOutputStream.putNextEntry(entry);
                                byteOutputStream = new ByteOutputStream();
                                byteOutputStream.write(inputStream);
                                byteOutputStream.writeTo(zipOutputStream);
                                byteOutputStream.close();
                            }
                            inputStream.close();
                        }
                    }
                }
            }
            zipOutputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 通用导出
     * @param mineGroup 根据文件目录分组后的数据
     * @param zipName 压缩包名称
     * @param title excel标题
     * @param response 响应结果
     */
    public  <T> void export(Map<String,List<T>> mineGroup , String zipName, String title, HttpServletResponse response,Class<?> cl,Map<String,List<Attachment>> attachmentGroup) {
        List<Workbook> workbooks=new ArrayList<>();
        List<String> excelNames=new ArrayList<>();
        List<String> parentName=new ArrayList<>();
        if(!ObjectUtils.isEmpty(mineGroup)){
            for(String key:mineGroup.keySet()){
                Workbook workbook= ExcelUtils.Excel(mineGroup.get(key),title,"sheet1",cl);
                workbooks.add(workbook);
                if(key.contains("\\")){
                    String name=key.substring(key.lastIndexOf("\\")+1) ;
                    excelNames.add(name);
                }else{
                    excelNames.add(key);
                }
                parentName.add(key);
            }
            exportZip(response,workbooks,zipName,excelNames, parentName,attachmentGroup);
        }
    }



    /**
     * 导入excel
     * @param filePath 文件地址
     * @param titleRows 标题行
     * @param headerRows
     * @param pojoClass 对象class
     * @param 
     * @return
     */
    public static <T> List<T> importExcel(String filePath,Integer titleRows,Integer headerRows, Class<T> pojoClass){
        if (StringUtils.isBlank(filePath)){
            return null;
        }
        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);
        params.setHeadRows(headerRows);
        List<T> list = null;
        try {
            list = ExcelImportUtil.importExcel(new File(filePath), pojoClass, params);
        }catch (NoSuchElementException e){
            e.printStackTrace();
            //throw new NotFoundException("模板不能为空");
        } catch (Exception e) {
            e.printStackTrace();
            //throw new NotFoundException(e.getMessage());
        }
        return list;
    }

    /**
     * 导入
     * @param file 需要导入的文件
     * @param titleRows 从第一行开始解析
     * @param headerRows 头部行下标
     * @param pojoClass 转化为对应的实体类
     * @param 
     * @return 返回解析后的实体类对象集合
     */
    public static <T> List<T> importExcel(MultipartFile file, Class<T> pojoClass, Integer titleRows, Integer headerRows, Integer sheetNum){
        if (file == null){
            return null;
        }
        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);
        params.setHeadRows(headerRows);
        params.setSheetNum(sheetNum);
        List<T> list = null;
        try {
            list = ExcelImportUtil.importExcel(file.getInputStream(), pojoClass, params);
        }catch (NoSuchElementException e){
            //throw new NotFoundException("excel文件不能为空");
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
            // throw new NotFoundException(e.getMessage());
        }
        return list;
    }



    /** Excel 导出 通过浏览器下载的形式
     *
     * @param response
     * @param workbook
     * @param fileName
     * @throws IOException
     */
    public static void export(HttpServletResponse response, Workbook workbook, String fileName) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setHeader("content-Type", "application/vnd.ms-excel");
        response.setHeader("Content-Disposition",
                "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        BufferedOutputStream bufferedOutPut = new BufferedOutputStream(response.getOutputStream());
        workbook.write(bufferedOutPut);
        bufferedOutPut.flush();
        bufferedOutPut.close();
    }

}

ExcelExportStylerUtil

package org.jeecg.utils.excel;

import cn.afterturn.easypoi.excel.export.styler.AbstractExcelExportStyler;
import org.apache.poi.ss.usermodel.*;

/**
 * 类说明
 *
 * @author chengyan
 * @date 2023/3/27
 */
public class ExcelExportStylerUtil extends AbstractExcelExportStyler {
    public ExcelExportStylerUtil(Workbook workbook) {
        super.createStyles(workbook);
    }
    @Override
    public CellStyle getHeaderStyle(short headerColor) {
        CellStyle titleStyle = workbook.createCellStyle();
        Font font = workbook.createFont();
        font.setFontHeightInPoints((short) 12);
        titleStyle.setFont(font);
        titleStyle.setAlignment(HorizontalAlignment.CENTER);         // 水平居中
        titleStyle.setVerticalAlignment(VerticalAlignment.CENTER);   // 上下居中
        titleStyle.setBorderBottom(BorderStyle.THIN); //下边框
        titleStyle.setBorderLeft(BorderStyle.THIN);//左边框
        titleStyle.setBorderTop(BorderStyle.THIN);//上边框
        titleStyle.setBorderRight(BorderStyle.THIN);//右边框
        return titleStyle;
    }

    @Override
    public CellStyle getTitleStyle(short color) {
        CellStyle titleStyle = workbook.createCellStyle();
        titleStyle.setAlignment(HorizontalAlignment.CENTER);         // 水平居中
        titleStyle.setVerticalAlignment(VerticalAlignment.CENTER);   // 上下居中
        titleStyle.setBorderBottom(BorderStyle.THIN); //下边框
        titleStyle.setBorderLeft(BorderStyle.THIN);//左边框
        titleStyle.setBorderTop(BorderStyle.THIN);//上边框
        titleStyle.setBorderRight(BorderStyle.THIN);//右边框
        titleStyle.setWrapText(true);
        return titleStyle;
    }

    @Override
    public CellStyle stringSeptailStyle(Workbook workbook, boolean isWarp) {
        CellStyle style = workbook.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER);         // 水平居中
        style.setVerticalAlignment(VerticalAlignment.CENTER);   // 上下居中
        style.setBorderBottom(BorderStyle.THIN); //下边框
        style.setBorderLeft(BorderStyle.THIN);//左边框
        style.setBorderTop(BorderStyle.THIN);//上边框
        style.setBorderRight(BorderStyle.THIN);//右边框
        style.setDataFormat(STRING_FORMAT);
        if (isWarp) {
            style.setWrapText(true);
        }
        return style;
    }

    @Override
    public CellStyle stringNoneStyle(Workbook workbook, boolean isWarp) {
        CellStyle style = workbook.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER);         // 水平居中
        style.setVerticalAlignment(VerticalAlignment.CENTER);   // 上下居中
        style.setBorderBottom(BorderStyle.THIN); //下边框
        style.setBorderLeft(BorderStyle.THIN);//左边框
        style.setBorderTop(BorderStyle.THIN);//上边框
        style.setBorderRight(BorderStyle.THIN);//右边框
        style.setDataFormat(STRING_FORMAT);
        if (isWarp) {
            style.setWrapText(true);
        }
        return style;
    }
}

3.导入模板下载

 /**
     * 下载模板
     *
     * @param response response
     * @throws Exception Exception
     */
    @ApiOperation(value = "下载模板", notes = "下载模板")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "excelName", required = true, value = "文件名")
    })
    @GetMapping("/downTemplate")
    public void downExcelTemplate(HttpServletResponse response,@RequestParam String  excelName ) throws Exception {
        HashMap<String, Object> map = new HashMap<>();
        TemplateExportParams params = new TemplateExportParams();
        Workbook template = WorkbookFactory.create(getClass().getClassLoader().getResourceAsStream("static/excel/"+excelName+".xlsx"));
        params.setTemplateWb(template);
        Workbook workbook = ExcelExportUtil.exportExcel(params, map);
        excelUtils.export(response,workbook,excelName+".xlsx");
    }

4.导入示例

@Override
    public Result<?> importExcel(MultipartFile file) {
        // 先将excel数据转换为list集合数据
        List<HazardSource> convertAfterList = ExcelUtils.importExcel(file,HazardSource.class,1,1,1);
        if(cn.easyes.common.utils.CollectionUtils.isEmpty(convertAfterList)){
            return Result.error("Excel数据为空,excel转化失败!");
        }
        // 过滤掉不必要的数据集合
        for (int i = 0; i < convertAfterList.size(); i++) {
            HazardSource convertAfter = convertAfterList.get(i);
            if(StringUtils.isEmpty(convertAfter.getBelongAreaName()) || StringUtils.isEmpty(convertAfter.getBelongMineName())){
                convertAfterList = convertAfterList.subList(0, i);
                break;
            }
        }
        StringBuffer lastMsg = new StringBuffer();
        lastMsg.append("共计【"+convertAfterList.size()+"】条!");
        // 当前行索引
        int index = 1;
        int successIndex = 0;
        for (HazardSource convertAfter : convertAfterList) {
            index ++;
           	// 定义验证逻辑
           	// 调用dao层插入数据
            successIndex ++;
        }
        if(successIndex == convertAfterList.size()){
            lastMsg.append("导入成功【"+successIndex+"】条!");
        } else {
            if(successIndex == convertAfterList.size()){
                lastMsg.append("导入成功【"+successIndex+"】条!");
            } else {
                lastMsg.append("注:导入失败【"+(convertAfterList.size() - successIndex)+"】条!导入成功【"+successIndex+"】条!");
            }
        }
        return Result.ok(lastMsg.toString());
    }

5.导出示例

 /**
	  *
	  * @param response
	  * @param hazardSource
	  * @param req
	  */
    //@RequiresPermissions("org:tbl_dws_hazard_source:exportXls")
    @RequestMapping(value = "/exportXls")
	public void exportXls(
			HttpServletResponse response,
			HazardSource hazardSource,
			HttpServletRequest req) {
		String zipName = "危险源信息管理";
		String title= "危险源信息表";
		QueryWrapper<HazardSource> queryWrapper =queryWrapperUtils.getQueryWrapper(hazardSource,null,null,req,"update_time","update_time");
		List<HazardSource> list=hazardSourceService.list(queryWrapper);
		// 获取所有需要创建的excel文件
		Map<String,List<HazardSource>> mineGroup = list.stream()
				.collect(Collectors.groupingBy(employ->employ.getBelongAreaName()+"\\"+employ.getBelongCompanyName()+"\\"+employ.getBelongMineName()));
		// 获取到当前业务下的附件信息
		List<Attachment>  attachmentList=queryWrapperUtils.getAttachments(CommonConstants.AttachmentbusinessType.HAZARD_SOURCE,null);
		Map<String,List<Attachment>> attachmentGroup = attachmentList.stream()
				.collect(Collectors.groupingBy(employ->employ.getBelongAreaName()+"\\"+employ.getBelongCompanyName()+"\\"+employ.getBelongMineName()));
		excelUtils.export(mineGroup,zipName,title,response, HazardSource.class,attachmentGroup);
	}

你可能感兴趣的:(excel,java,开发语言)