Jxls excel 导出带图片

Jxls excel 导出带图片

Jxls excel 导出带图片_第1张图片
Jxls excel 导出带图片_第2张图片
Jxls excel 导出带图片_第3张图片
依赖

<!-- jxls poi 根据模板导出-->
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-scratchpad</artifactId>
        <version>3.15</version>
    </dependency>
    <dependency>
        <groupId>net.sf.jxls</groupId>
        <artifactId>jxls-core</artifactId>
        <version>1.0</version>
    </dependency>
        <dependency>
            <groupId>org.jxls</groupId>
            <artifactId>jxls</artifactId>
            <version>2.4.6</version>
        </dependency>
        <dependency>
            <groupId>org.jxls</groupId>
            <artifactId>jxls-poi</artifactId>
            <version>1.0.15</version>
        </dependency>
        <dependency>
            <groupId>org.jxls</groupId>
            <artifactId>jxls-jexcel</artifactId>
            <version>1.0.7</version>
        </dependency>

使用

    public void exportMember(PageQueryMemberListReqVO pageQueryMemberListReqVO, HttpServletResponse response) throws Exception {
        try {
            List<Member> list = memberService.lambdaQuery().like(StringUtils.isNotBlank(pageQueryMemberListReqVO.getName()),Member::getName,pageQueryMemberListReqVO.getName())
                    .eq(StringUtils.isNotBlank(pageQueryMemberListReqVO.getEducationBackground()),Member::getEducationBackground,pageQueryMemberListReqVO.getEducationBackground())
                    .eq(ObjectUtil.isNotNull(pageQueryMemberListReqVO.getOrgCoding()),Member::getOrgCoding,pageQueryMemberListReqVO.getOrgCoding())
                    .eq(StringUtils.isNotBlank(pageQueryMemberListReqVO.getPoliticalStatus()),Member::getPoliticalStatus,pageQueryMemberListReqVO.getPoliticalStatus())
                    .eq(StringUtils.isNotBlank(pageQueryMemberListReqVO.getPracticeStatus()),Member::getPracticeStatus,pageQueryMemberListReqVO.getPracticeStatus())
                    .eq(StringUtils.isNotBlank(pageQueryMemberListReqVO.getTakeForeign()),Member::getTakeForeign,pageQueryMemberListReqVO.getTakeForeign())
                    .list();
            for(Member member:list){
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                // -----------涉外公证资格取得时间-------------------------------//
                if(null!=member.getTakeForeignTime()) {
                    try {
                        member.setTakeForeignTimeStr(simpleDateFormat.format(member.getTakeForeignTime()));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                // -----------是否取得涉外公证资格-------------------------------//
                if(1==member.getTakeForeign()){
                    member.setTakeForeignStr("是");
                }else if(0==member.getTakeForeign()){
                    member.setTakeForeignStr("否");
                }else {
                    member.setTakeForeignStr(member.getTakeForeign().toString());
                }
                // -----------执业证书颁发时间-------------------------------//
                if(null!=member.getCertificateTime()) {
                    try {
                        member.setCertificateTimeStr(simpleDateFormat.format(member.getCertificateTime()));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                // -----------专业职称-------------------------------//
                try {
                    String name = ProfessionalTitleUtils.getProfessionalTitleName(member.getProfessionalTitle());
                    if(StringUtils.isNotBlank(name)){
                        member.setProfessionalTitle(name);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                // -----------参加工作时间-------------------------------//
                if(null!=member.getFirstJobTime()) {
                    try {
                        member.setFirstJobTimeStr(simpleDateFormat.format(member.getFirstJobTime()));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                // -----------人员编制-------------------------------//
                try {
                    String name = StaffingUtils.getStaffingName(member.getStaffing());
                    if(StringUtils.isNotBlank(name)){
                        member.setStaffing(name);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                // -----------协会职务-------------------------------//
                try {
                    String name = AssociationJobUtils.getAssociationJobName(member.getAssociationJob());
                    if(StringUtils.isNotBlank(name)){
                        member.setAssociationJob(name);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

                // -----------机构职务-------------------------------//
                try {
                    String name = OrgJobUtils.getOrgJobName(member.getOrgJob());
                    if(StringUtils.isNotBlank(name)){
                        member.setOrgJob(name);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

                // -----------专业-------------------------------//
                try {
                    String name = MajorUtils.getMajorName(member.getMajor());
                    if(StringUtils.isNotBlank(name)){
                        member.setMajor(name);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                // -----------学位-------------------------------//
                try {
                    String name = DegreeUtils.getDegreeName(member.getDegree());
                    if(StringUtils.isNotBlank(name)){
                        member.setDegree(name);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                // -----------学历-------------------------------//
                try {
                    String name = EducationBackgroundUtils.getEducationBackgroundName(member.getEducationBackground());
                    if(StringUtils.isNotBlank(name)){
                        member.setEducationBackground(name);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                // -----------毕业时间-------------------------------//
                if(null!=member.getGraduateTime()) {
                    try {
                        member.setTakeForeignTimeStr(simpleDateFormat.format(member.getGraduateTime()));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                // -----------政治面貌-------------------------------//
                try {
                    String name = PoliticalStatusUtils.getPoliticalStatusName(member.getPoliticalStatus());
                    if(StringUtils.isNotBlank(name)){
                        member.setPoliticalStatus(name);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

                // -----------民族-------------------------------//
                try {
                    String name = ChineseNationalityCodeUtil.getNationalityName(Integer.parseInt(member.getNation()));
                    if(StringUtils.isNotBlank(name)){
                        member.setNation(name);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                // -----------出生日期-------------------------------//
                if(null!=member.getBirthday()) {
                    try {
                        member.setBirthdayStr(simpleDateFormat.format(member.getBirthday()));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                // -----------性别-------------------------------//
                if("1".equals(member.getGender())) {
                    member.setGender("男");
                }else if("2".equals(member.getGender())) {
                    member.setGender("女");
                }
                // -----------照片-------------------------------//
                try {
                    String file=member.getPhoto();
                    if (file.contains("data:")) {
                        int start = file.indexOf(",");
                        file = file.substring(start + 1);
                    }
                    final Base64.Decoder decoder = Base64.getDecoder();
                    file = file.replaceAll("\r|\n", "");
                    file = file.trim();
                    byte[] bytes = decoder.decode(file);
                    member.setPhotoByte(bytes);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            Map mapList = new HashMap<String, Object>();
            mapList.put("lists",list);
           JxlsUtil.exportExcel(exportMemberModel,"公证员基本信息表.xls",mapList,response);
           // TemplateExcelUtils.downLoadExcel("公证员基本信息表.xls",exportMemberModel,mapList,response);
        }catch (Exception e){
           log.error("导出公证员信息失败",e);
            if(e instanceof ServiceException){
                throw e;
            }else {
                throw new ServiceException(ErrorCode.ERROR.getCode(),"导出公证员信息失败");
            }
        }
    }

工具类

package com.fajiajia.notary.util.excel;

import org.apache.commons.collections4.*;
import org.jxls.builder.xls.*;
import org.jxls.common.*;
import org.jxls.transform.Transformer;
import org.jxls.transform.jexcel.*;
import org.jxls.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.Objects;

public class JxlsUtil {
    private static Logger log = LoggerFactory.getLogger(JxlsUtil.class);
    private static final String CONTENT_TYPE = "application/vnd.ms-excel";


    /**
     * 导出Excel
     *
     * @param templatePath   模板路径
     * @param exportFileName
     * Name 导出的文件名
     * @param data           数据集合
     * @param response
     * @throws IOException
     */
    public static void exportExcel(String templatePath, String exportFileName, Map<String, Object> data, HttpServletResponse response) {
        InputStream is =null;
        ServletOutputStream os=null;
        try {
            exportFileName = URLEncoder.encode(exportFileName, "UTF-8");
            response.setContentType(CONTENT_TYPE);
            response.setHeader("Content-Disposition", "attachment;filename*=utf-8'zh_cn'" + exportFileName + ".xls");
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            Context context = new Context(data);
            os = response.getOutputStream();
            is = new FileInputStream(templatePath);
            JxlsHelper.getInstance().processTemplate(is, os, context);

        } catch (Exception e) {
            log.error("excel导出异常", e);
        }finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 导出Excel
     *
     * @param sheetNameList   需要删除的sheet
     * @param templatePath   模板路径
     * @param exportFileName 导出的文件名
     * @param data           数据集合
     * @param response
     * @throws IOException
     */
    public static void exportExcel(List<String> sheetNameList, String templatePath, String exportFileName, Map<String, Object> data, HttpServletResponse response) {
        InputStream is =null;
        ServletOutputStream os=null;
        try {
            exportFileName = URLEncoder.encode(exportFileName, "UTF-8");
            response.setContentType(CONTENT_TYPE);
            response.setHeader("Content-Disposition", "attachment;filename*=utf-8'zh_cn'" + exportFileName + ".xls");
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            Context context = new Context(data);
            os = response.getOutputStream();
            is = new FileInputStream(templatePath);
            JxlsHelper jxlsHelper = JxlsHelper.getInstance();
            Transformer transformer = jxlsHelper.createTransformer(is, os);
            if (CollectionUtils.isNotEmpty(sheetNameList)){
                sheetNameList.forEach(transformer::deleteSheet);
            }
//            jxlsHelper.processTemplate(is, os, context);
            jxlsHelper.setUseFastFormulaProcessor(false).processTemplate(context, transformer);
            is.close();
        } catch (Exception e) {
            log.error("excel导出异常", e);
        }finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 导出Excel
     *
     * @param templatePath 模板路径
     * @param data         数据集合
     * @throws IOException
     */
    public static InputStream exportExcel(String templatePath, Map<String, Object> data) {
        InputStream excelStream = null;
        try {
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            JexcelContext context = new JexcelContext(data);
            InputStream is = new FileInputStream(templatePath);
            JxlsHelper.getInstance().processTemplate(is, os, context);
            is.close();
            excelStream = new ByteArrayInputStream(os.toByteArray());
            os.close();
        } catch (Exception e) {
            log.error("excel导出异常", e);
        }
        return excelStream;
    }

    public static void closedInputStream(InputStream inputStream) {
        try {
            if (Objects.nonNull(inputStream)) {
                inputStream.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
            log.error("关闭流管道异常");
        }
    }


    public static void closedOutputStream(OutputStream outputStream) {
        try {
            if (Objects.nonNull(outputStream)) {
                outputStream.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
            log.error("关闭流管道异常");
        }
    }

    /**
     * 将InputStream写入本地文件
     * @param destination 写入本地目录
     * @param input    输入流
     * @throws IOException
     */
    private static void writeToLocal(String destination, InputStream input)
            throws IOException {
        int index;
        byte[] bytes = new byte[1024];
        FileOutputStream downloadFile = new FileOutputStream(destination);
        while ((index = input.read(bytes)) != -1) {
            downloadFile.write(bytes, 0, index);
            downloadFile.flush();
        }
        downloadFile.close();
        input.close();
    }
}



效果
Jxls excel 导出带图片_第4张图片

你可能感兴趣的:(java,Jxls,excel,导出图片)