excel按模板导出

接口:导出zip 图片,还是导出人员的所有excel 信息:

@ApiOperation(value = "selectByPrimaryKey", notes = "")
@RequestMapping("/exportPhoto")
@UserPermission(userIdentity="admin")
//@Transactional
public Result exportPhoto(String userIds,String idCardTrue,String userPhotoTrue,String excelTrue,HttpServletRequest request, HttpServletResponse response) throws IOException {
    SFTPUtil sftp = new SFTPUtil(RsaHelper.decrypt(userName),RsaHelper.decrypt(passWord),host,port);
    String imgPath = this.getClass().getResource("/").getPath()+"img";
    try {
        List<String> userIdList =new ArrayList<>();
        if(userIds!=null && !userIds.equals("")) {
            String[] split = userIds.split("\\!");
            for (int i = 0; i < split.length; i++) {
                userIdList.add(split[i]);
            }
        }
            if(idCardTrue.equals("true")) {
                List<EmplUserImag> emplUserImagList = emplUserImagService.selectByPrimaryKey(userIdList);
                //获取ftp服务器文件Files 集合
                sftp.login();
                ServletOutputStream sos = response.getOutputStream();
                sftp.downloadFiles(imgPath,basePath,directory,emplUserImagList,"noUserPhoto",sos);
                sftp.logout();
            }
            if(userPhotoTrue.equals("true")){
                List<EmplUserImag> emplUserImagList = emplUserImagService.selectByPrimaryKey(userIdList);
                sftp.login();
                ServletOutputStream sos = response.getOutputStream();
                sftp.downloadFiles(imgPath,basePath,directory,emplUserImagList,"userPhoto",sos);
                sftp.logout();
            }
            if(excelTrue.equals("true")){
                List<ExportExcelEmplUser> euList = exportExcelEmplUserService.selectAll(userIdList);
                List<ExportExcelEmplUserEducation> eueList = exportExcelEmplUserEducationService.selectAll(userIdList);
                List<ExportExcelEmplUserWork> euwList = exportExcelEmplUserWorkService.selectAll(userIdList);
                List<ExportExcelEmplUserPolitics> eupList = exportExcelEmplUserPoliticsService.selectAll(userIdList);
                String path = this.getClass().getResource("/").getPath()+ "template/template.xls";
                ExportExcelUtil2.exportExcel(path,euList,eueList,euwList,eupList,request,response);
            }
    }catch (ServiceException exception){
        throw new ServiceException("导出失败");
    } catch (Exception e) {
        e.printStackTrace();
        logger.info("导出失败");
    }
    return ResultGenerator.genSuccessResult("导出成功");
}

导出excel 工具类:

package com.unicom.sh.pom.file.util;

import com.unicom.sh.pom.exception.ServiceException;
import com.unicom.sh.pom.service.domain.ExportExcelEmplUser;
import com.unicom.sh.pom.service.domain.ExportExcelEmplUserEducation;
import com.unicom.sh.pom.service.domain.ExportExcelEmplUserPolitics;
import com.unicom.sh.pom.service.domain.ExportExcelEmplUserWork;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.Charset;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @description: excel导出对象数据
 * @author: Captain
 * @create: 2018-11-07 14:36
 */
public class ExportExcelUtil2 {
    private final static Logger logger = LoggerFactory.getLogger(ExportExcelUtil2.class);

    private static final String EXCEL_SUFFIX_XLSX = ".xlsx";

    private static final String EXCEL_SUFFIX_XLS = ".xls";

    private static final String EXCEL_SUFFIX_ZIP = ".zip";

    private static String[] IEBrowserSignals = {"MSIE", "Trident", "Edge"};

    /**
     * 确认浏览器类型
     * @param request
     * @return
     */
    public static boolean isMSBrowser(HttpServletRequest request) {
        String userAgent = request.getHeader("User-Agent");
        for (String signal : IEBrowserSignals) {
            if (userAgent.contains(signal))
                return true;
        }
        return false;
    }

    /**
     * 普通excel导出
     * @param fileName 文件名称
     * @param wb        工作簿
     * @param request   请求
     * @param response  响应
     */
    public static void exportCommonExcel(String fileName, HSSFWorkbook wb, HttpServletRequest request, HttpServletResponse response){
        OutputStream out = null;
        fileName += EXCEL_SUFFIX_XLS;
        try {
            response.setContentType("application/vnd.ms-excel");
            boolean isMSIE = isMSBrowser(request);
            if (isMSIE) {
                fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
            } else {
                fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
            }
            response.setHeader("Content-disposition", "attachment;filename=\"" + fileName + "\"");
            out = response.getOutputStream();
            wb.write(out);
        } catch (IOException e) {
            throw new ServiceException("IO流关闭异常", e);
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    logger.info("流关闭异常", e);
                }
            }
        }
    }

    /**
     * 按模板导出数据
     * @param request
     * @param response
     */
    public static void exportExcel(String path, List<ExportExcelEmplUser> euList, List<ExportExcelEmplUserEducation> eueList, List<ExportExcelEmplUserWork> euwList,  List<ExportExcelEmplUserPolitics> eupList, HttpServletRequest request, HttpServletResponse response){
            File newFile = new File(path);
            String fileName = "申请员工号";
            InputStream is = null;
            HSSFWorkbook workbook = null;
        try {
            is = new FileInputStream(newFile);
            workbook = new HSSFWorkbook(is);
            //获取第一个sheet
            Sheet euSheet = workbook.getSheetAt(0);
            Sheet eueSheet = workbook.getSheetAt(1);
            Sheet euwSheet = workbook.getSheetAt(2);
            Sheet eupSheet = workbook.getSheetAt(3);
            //基本信息
            if(!euList.isEmpty()){
                for (int k = 0; k < euList.size(); k++) {
                    Row row = euSheet.createRow(k+1);
                    row.createCell(0).setCellValue(euList.get(k).getUserName());
                    row.createCell(1).setCellValue(euList.get(k).getUserSpelling());
                    row.createCell(2).setCellValue(euList.get(k).getIdCard());
                    row.createCell(3).setCellValue(DateUtil.formatDateTime(euList.get(k).getBirthday()));
                    row.createCell(4).setCellValue(euList.get(k).getSex());
                    row.createCell(5).setCellValue(euList.get(k).getPermanentType());
                    row.createCell(6).setCellValue(euList.get(k).getPermanentAddress());
                    row.createCell(7).setCellValue(DateUtil.formatDateTime(euList.get(k).getEntryDate()));//入职日期
                    row.createCell(8).setCellValue(euList.get(k).getUserOrganization());
                    row.createCell(9).setCellValue(euList.get(k).getUserPost());
                    row.createCell(10).setCellValue(euList.get(k).getUserPostOrName());
                    row.createCell(11).setCellValue(euList.get(k).getClassificationType());
                    row.createCell(12).setCellValue(euList.get(k).getRecruitanduseType());
                    row.createCell(13).setCellValue(euList.get(k).getUserType());
                    row.createCell(14).setCellValue(DateUtil.formatDateTime(euList.get(k).getEntryDate()));
                    row.createCell(15).setCellValue(euList.get(k).getNewJoinEnterprise());
                    row.createCell(16).setCellValue(euList.get(k).getNewSonJoinEnterprise());
                    row.createCell(17).setCellValue(euList.get(k).getNewExplainJoinEnterprise());
                    row.createCell(18).setCellValue(euList.get(k).getIsEmigrate());
                    row.createCell(19).setCellValue(euList.get(k).getIsDisability());
                    row.createCell(20).setCellValue(euList.get(k).getBloodType());
                    row.createCell(21).setCellValue(euList.get(k).getNationality());
                    row.createCell(22).setCellValue(euList.get(k).getNation());
                    row.createCell(23).setCellValue(euList.get(k).getNativePlace());
                    row.createCell(24).setCellValue(euList.get(k).getOldHome());
                    row.createCell(25).setCellValue(euList.get(k).getIsMarriage());
                    row.createCell(26).setCellValue(euList.get(k).getIsHealthy());
                    row.createCell(27).setCellValue(DateUtil.formatDateTime(euList.get(k).getEntryDate()));
                    row.createCell(28).setCellValue(euList.get(k).getWorkBeginDate());
                    row.createCell(29).setCellValue(euList.get(k).getOperationMode());
                    row.createCell(30).setCellValue(euList.get(k).getWorkBeginDate());
                    row.createCell(31).setCellValue(euList.get(k).getInterruptedWorkTime());
                    row.createCell(32).setCellValue(euList.get(k).getEstimatedRetirementTime());
                    row.createCell(33).setCellValue(euList.get(k).getSocialSecurity());
                    row.createCell(34).setCellValue(euList.get(k).getSpecialExpertise());
                    row.createCell(35).setCellValue(euList.get(k).getMail());
                    row.createCell(36).setCellValue(euList.get(k).getMobilePhone());
                    row.createCell(37).setCellValue(euList.get(k).getBusinessUnit());
                    row.createCell(38).setCellValue(euList.get(k).getUnitPerson());
                }
            }
            //教育信息
            if(!eueList.isEmpty()){
                for(int e=0;e<eueList.size();e++){
                    Row row = eueSheet.createRow(e+1);
                    row.createCell(0).setCellValue(eueList.get(e).getUserName());
                    row.createCell(1).setCellValue(eueList.get(e).getIdCard());
                    row.createCell(2).setCellValue(eueList.get(e).getEducationSchoolName());
                    row.createCell(3).setCellValue(eueList.get(e).getEducationIsReturnees());
                    row.createCell(4).setCellValue(DateUtil.formatDateTime(eueList.get(e).getEducationBeginDate()));
                    row.createCell(5).setCellValue(DateUtil.formatDateTime(eueList.get(e).getEducationBeginEnd()));
                    row.createCell(6).setCellValue(eueList.get(e).getEducationName());
                    row.createCell(7).setCellValue(eueList.get(e).getEducationIsHighest().equals("1")?"是":"否");
                    row.createCell(8).setCellValue(eueList.get(e).getEducationDegree());
                    row.createCell(9).setCellValue(eueList.get(e).getEducationType());
                    row.createCell(10).setCellValue(eueList.get(e).getEducationDegreeIsHighest().equals("1")?"是":"否");
                    row.createCell(11).setCellValue(eueList.get(e).getEducationMajorType());
                    row.createCell(12).setCellValue(eueList.get(e).getEducationMajor());
                    row.createCell(13).setCellValue(eueList.get(e).getEducationShape());
                    row.createCell(14).setCellValue(eueList.get(e).getRemarks());
                    row.createCell(15).setCellValue(eueList.get(e).getRemarks());
                    row.createCell(16).setCellValue(eueList.get(e).getRemarks());
                    row.createCell(17).setCellValue(eueList.get(e).getRemarks());
                    row.createCell(18).setCellValue(eueList.get(e).getRemarks());
                    row.createCell(19).setCellValue(eueList.get(e).getRemarks());
                    row.createCell(20).setCellValue(eueList.get(e).getRemarks());
                    row.createCell(21).setCellValue(eueList.get(e).getRemarks());
                    row.createCell(22).setCellValue(eueList.get(e).getRemarks());
                    row.createCell(23).setCellValue(eueList.get(e).getRemarks());
                }
            }
            //工作经历
            if(!euwList.isEmpty()){
                for(int w=0;w<euwList.size();w++) {
                    Row row = euwSheet.createRow(w + 1);
                    row.createCell(0).setCellValue(euwList.get(w).getUserName());
                    row.createCell(1).setCellValue(euwList.get(w).getIdCard());
                    row.createCell(2).setCellValue(DateUtil.formatDateTime(euwList.get(w).getWorkBeginDate()));
                    row.createCell(3).setCellValue(DateUtil.formatDateTime(euwList.get(w).getWorkEndDate()));
                    row.createCell(4).setCellValue(euwList.get(w).getWorkCompany());
                    row.createCell(5).setCellValue(euwList.get(w).getWorkDeptno());
                    row.createCell(6).setCellValue(euwList.get(w).getWorkJob());
                    row.createCell(7).setCellValue(euwList.get(w).getIsEnterprise());
                    row.createCell(8).setCellValue(euwList.get(w).getWorkUnit());
                    row.createCell(9).setCellValue(euwList.get(w).getSpecializes());
                }
            }
            if(!eupList.isEmpty()){
                for(int p=0;p<eupList.size();p++){
                    Row row = eupSheet.createRow(p+1);
                    row.createCell(0).setCellValue(eupList.get(p).getUserName());
                    row.createCell(1).setCellValue(eupList.get(p).getIdCard());
                    row.createCell(2).setCellValue(DateUtil.formatDateTime(eupList.get(p).getEntryDate()));
                    row.createCell(3).setCellValue(eupList.get(p).getRemarks());
                    row.createCell(4).setCellValue(eupList.get(p).getPoliticsStage());
                    row.createCell(5).setCellValue(DateUtil.formatDateTime(eupList.get(p).getPoliticsBeginDate()));
                    row.createCell(6).setCellValue(eupList.get(p).getState());
                    row.createCell(7).setCellValue(eupList.get(p).getIsCompany());
                    row.createCell(8).setCellValue(eupList.get(p).getPartyGroupPost());
                    row.createCell(9).setCellValue(eupList.get(p).getIntroducer());
                    row.createCell(10).setCellValue(eupList.get(p).getRemarks());
                    row.createCell(11).setCellValue(eupList.get(p).getWitness());
                }
            }
            ExportExcelUtil2.exportCommonExcel(fileName,workbook,request,response);
        }catch (IOException e){
            throw new ServiceException("导出异常");
        }
    }

    /**
     * 将excel以zip格式导出
     * @param fileName 文件名称
     * @param wb        工作簿
     * @param request   请求
     * @param response  响应
     */
    public static void exportExcelToZipFIle(String fileName, HSSFWorkbook wb, HttpServletRequest request, HttpServletResponse response){
        OutputStream out = null;
        ZipOutputStream zip = null;
        String fileName1 = fileName + EXCEL_SUFFIX_XLS;
        String fileName2 = fileName + EXCEL_SUFFIX_ZIP;
        try {
            response.setContentType("APPLICATION/OCTET-STREAM");
            boolean isMSIE = isMSBrowser(request);
            if (isMSIE) {
                fileName2 = java.net.URLEncoder.encode(fileName2, "UTF-8");
            } else {
                fileName2 = new String(fileName2.getBytes("UTF-8"), "ISO-8859-1");
            }
            response.setHeader("Content-disposition", "attachment;filename=\"" + fileName2 + "\"");
            out = response.getOutputStream();
            zip = new ZipOutputStream(out, Charset.forName("UTF-8"));
            ZipEntry entry = new ZipEntry(fileName1);//设置压缩包中文件的名字
            zip.putNextEntry(entry);
            wb.write(zip);
            zip.flush();
        } catch (IOException e) {
            throw new ServiceException("流关闭异常", e);
        } finally {
            if (zip != null) {
                try {
                    zip.close();
                } catch (IOException e) {
                    throw new ServiceException("压缩流关闭异常", e);
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    throw new ServiceException("流关闭异常", e);
                }
            }
        }
    }

    /**
     * excel导出模板数据
     * @param fileName  文件名
     * @param path      文件路径
     * @param response  响应
     */
    public static void exportExcelTemplate(String fileName, String path, HttpServletRequest request, HttpServletResponse response){
        File file = new File(path);
        InputStream in = null;
        OutputStream out = null;
        fileName += EXCEL_SUFFIX_XLSX;
        try {
            response.setContentType("application/octet-stream");
            boolean isMSIE = isMSBrowser(request);
            if (isMSIE) {
                fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
            } else {
                fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
            }
            response.setHeader("Content-disposition", "attachment;filename=\"" + fileName + "\"");
            in = new FileInputStream(file);
            out = response.getOutputStream();
            int b;
            while ((b = in.read()) != -1){
                out.write(b);
            }
        } catch (IOException e) {
            throw new ServiceException("流IO异常", e);
        } finally {
            if (in != null){
                try {
                    in.close();
                } catch (IOException e) {
                    throw new ServiceException("流关闭异常", e);
                }
            }
            if (out != null){
                try {
                    out.close();
                    out.flush();
                } catch (IOException e) {
                    throw new ServiceException("流关闭异常", e);
                }
            }
        }
    }

}
写入excel模板代码:
/**
 * 按模板导出数据
 * @param request
 * @param response
 */
public static void exportExcel(String path, List<ExportExcelEmplUser> euList, List<ExportExcelEmplUserEducation> eueList, List<ExportExcelEmplUserWork> euwList,  List<ExportExcelEmplUserPolitics> eupList, HttpServletRequest request, HttpServletResponse response){
        File newFile = new File(path);
        String fileName = "申请员工号";
        InputStream is = null;
        HSSFWorkbook workbook = null;
    try {
        is = new FileInputStream(newFile);
        workbook = new HSSFWorkbook(is);
        //获取第一个sheet
        Sheet euSheet = workbook.getSheetAt(0);
        Sheet eueSheet = workbook.getSheetAt(1);
        Sheet euwSheet = workbook.getSheetAt(2);
        Sheet eupSheet = workbook.getSheetAt(3);
        //基本信息
        if(!euList.isEmpty()){
            for (int k = 0; k < euList.size(); k++) {
                Row row = euSheet.createRow(k+1);
                row.createCell(0).setCellValue(euList.get(k).getUserName());
                row.createCell(1).setCellValue(euList.get(k).getUserSpelling());
                row.createCell(2).setCellValue(euList.get(k).getIdCard());
                row.createCell(3).setCellValue(DateUtil.formatDateTime(euList.get(k).getBirthday()));
                row.createCell(4).setCellValue(euList.get(k).getSex());
                row.createCell(5).setCellValue(euList.get(k).getPermanentType());
                row.createCell(6).setCellValue(euList.get(k).getPermanentAddress());
                row.createCell(7).setCellValue(DateUtil.formatDateTime(euList.get(k).getEntryDate()));//入职日期
                row.createCell(8).setCellValue(euList.get(k).getUserOrganization());
                row.createCell(9).setCellValue(euList.get(k).getUserPost());
                row.createCell(10).setCellValue(euList.get(k).getUserPostOrName());
                row.createCell(11).setCellValue(euList.get(k).getClassificationType());
                row.createCell(12).setCellValue(euList.get(k).getRecruitanduseType());
                row.createCell(13).setCellValue(euList.get(k).getUserType());
                row.createCell(14).setCellValue(DateUtil.formatDateTime(euList.get(k).getEntryDate()));
                row.createCell(15).setCellValue(euList.get(k).getNewJoinEnterprise());
                row.createCell(16).setCellValue(euList.get(k).getNewSonJoinEnterprise());
                row.createCell(17).setCellValue(euList.get(k).getNewExplainJoinEnterprise());
                row.createCell(18).setCellValue(euList.get(k).getIsEmigrate());
                row.createCell(19).setCellValue(euList.get(k).getIsDisability());
                row.createCell(20).setCellValue(euList.get(k).getBloodType());
                row.createCell(21).setCellValue(euList.get(k).getNationality());
                row.createCell(22).setCellValue(euList.get(k).getNation());
                row.createCell(23).setCellValue(euList.get(k).getNativePlace());
                row.createCell(24).setCellValue(euList.get(k).getOldHome());
                row.createCell(25).setCellValue(euList.get(k).getIsMarriage());
                row.createCell(26).setCellValue(euList.get(k).getIsHealthy());
                row.createCell(27).setCellValue(DateUtil.formatDateTime(euList.get(k).getEntryDate()));
                row.createCell(28).setCellValue(euList.get(k).getWorkBeginDate());
                row.createCell(29).setCellValue(euList.get(k).getOperationMode());
                row.createCell(30).setCellValue(euList.get(k).getWorkBeginDate());
                row.createCell(31).setCellValue(euList.get(k).getInterruptedWorkTime());
                row.createCell(32).setCellValue(euList.get(k).getEstimatedRetirementTime());
                row.createCell(33).setCellValue(euList.get(k).getSocialSecurity());
                row.createCell(34).setCellValue(euList.get(k).getSpecialExpertise());
                row.createCell(35).setCellValue(euList.get(k).getMail());
                row.createCell(36).setCellValue(euList.get(k).getMobilePhone());
                row.createCell(37).setCellValue(euList.get(k).getBusinessUnit());
                row.createCell(38).setCellValue(euList.get(k).getUnitPerson());
            }
        }
        //教育信息
        if(!eueList.isEmpty()){
            for(int e=0;e<eueList.size();e++){
                Row row = eueSheet.createRow(e+1);
                row.createCell(0).setCellValue(eueList.get(e).getUserName());
                row.createCell(1).setCellValue(eueList.get(e).getIdCard());
                row.createCell(2).setCellValue(eueList.get(e).getEducationSchoolName());
                row.createCell(3).setCellValue(eueList.get(e).getEducationIsReturnees());
                row.createCell(4).setCellValue(DateUtil.formatDateTime(eueList.get(e).getEducationBeginDate()));
                row.createCell(5).setCellValue(DateUtil.formatDateTime(eueList.get(e).getEducationBeginEnd()));
                row.createCell(6).setCellValue(eueList.get(e).getEducationName());
                row.createCell(7).setCellValue(eueList.get(e).getEducationIsHighest().equals("1")?"是":"否");
                row.createCell(8).setCellValue(eueList.get(e).getEducationDegree());
                row.createCell(9).setCellValue(eueList.get(e).getEducationType());
                row.createCell(10).setCellValue(eueList.get(e).getEducationDegreeIsHighest().equals("1")?"是":"否");
                row.createCell(11).setCellValue(eueList.get(e).getEducationMajorType());
                row.createCell(12).setCellValue(eueList.get(e).getEducationMajor());
                row.createCell(13).setCellValue(eueList.get(e).getEducationShape());
                row.createCell(14).setCellValue(eueList.get(e).getRemarks());
                row.createCell(15).setCellValue(eueList.get(e).getRemarks());
                row.createCell(16).setCellValue(eueList.get(e).getRemarks());
                row.createCell(17).setCellValue(eueList.get(e).getRemarks());
                row.createCell(18).setCellValue(eueList.get(e).getRemarks());
                row.createCell(19).setCellValue(eueList.get(e).getRemarks());
                row.createCell(20).setCellValue(eueList.get(e).getRemarks());
                row.createCell(21).setCellValue(eueList.get(e).getRemarks());
                row.createCell(22).setCellValue(eueList.get(e).getRemarks());
                row.createCell(23).setCellValue(eueList.get(e).getRemarks());
            }
        }
        //工作经历
        if(!euwList.isEmpty()){
            for(int w=0;w<euwList.size();w++) {
                Row row = euwSheet.createRow(w + 1);
                row.createCell(0).setCellValue(euwList.get(w).getUserName());
                row.createCell(1).setCellValue(euwList.get(w).getIdCard());
                row.createCell(2).setCellValue(DateUtil.formatDateTime(euwList.get(w).getWorkBeginDate()));
                row.createCell(3).setCellValue(DateUtil.formatDateTime(euwList.get(w).getWorkEndDate()));
                row.createCell(4).setCellValue(euwList.get(w).getWorkCompany());
                row.createCell(5).setCellValue(euwList.get(w).getWorkDeptno());
                row.createCell(6).setCellValue(euwList.get(w).getWorkJob());
                row.createCell(7).setCellValue(euwList.get(w).getIsEnterprise());
                row.createCell(8).setCellValue(euwList.get(w).getWorkUnit());
                row.createCell(9).setCellValue(euwList.get(w).getSpecializes());
            }
        }
        if(!eupList.isEmpty()){
            for(int p=0;p<eupList.size();p++){
                Row row = eupSheet.createRow(p+1);
                row.createCell(0).setCellValue(eupList.get(p).getUserName());
                row.createCell(1).setCellValue(eupList.get(p).getIdCard());
                row.createCell(2).setCellValue(DateUtil.formatDateTime(eupList.get(p).getEntryDate()));
                row.createCell(3).setCellValue(eupList.get(p).getRemarks());
                row.createCell(4).setCellValue(eupList.get(p).getPoliticsStage());
                row.createCell(5).setCellValue(DateUtil.formatDateTime(eupList.get(p).getPoliticsBeginDate()));
                row.createCell(6).setCellValue(eupList.get(p).getState());
                row.createCell(7).setCellValue(eupList.get(p).getIsCompany());
                row.createCell(8).setCellValue(eupList.get(p).getPartyGroupPost());
                row.createCell(9).setCellValue(eupList.get(p).getIntroducer());
                row.createCell(10).setCellValue(eupList.get(p).getRemarks());
                row.createCell(11).setCellValue(eupList.get(p).getWitness());
            }
        }
        ExportExcelUtil2.exportCommonExcel(fileName,workbook,request,response);
    }catch (IOException e){
        throw new ServiceException("导出异常");
    }
}

模板放resources / template 文件夹中

顺便记录一下从 sftp 上下载文件打包到zip中导出吧

sftp 工具类:

package com.unicom.sh.pom.file.util;

import java.io.File;
import java.io.FileNotFoundException;  
import java.io.FileOutputStream;  
import java.io.IOException;  
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.Vector;
import com.unicom.sh.pom.service.domain.EmplUserImag;
import org.apache.poi.util.IOUtils;
import com.jcraft.jsch.Channel;  
import com.jcraft.jsch.ChannelSftp;  
import com.jcraft.jsch.JSch;  
import com.jcraft.jsch.JSchException;  
import com.jcraft.jsch.Session;  
import com.jcraft.jsch.SftpException;

import javax.servlet.ServletOutputStream;

/** 
* 类说明 sftp工具类
*/
public class SFTPUtil {

    private ChannelSftp sftp;

    private Session session;
    /** SFTP 登录用户名*/
    private String username;
    /** SFTP 登录密码*/
    private String password;
    /** 私钥 */
    private String privateKey;
    /** SFTP 服务器地址IP地址*/
    private String host;
    /** SFTP 端口*/
    private int port;

    private String basePath;
    /** SFTP 端口*/
    private String directory;

    /**
     * 构造基于密码认证的sftp对象
     */
    public SFTPUtil(String username, String password, String host, int port) {
        this.username = username;
        this.password = password;
        this.host = host;
        this.port = port;
    }
    /**
     * 构造基于密码认证的sftp对象
     */
    public SFTPUtil(String username, String password, String host, int port,String basePath,String directory) {
        this.username = username;
        this.password = password;
        this.host = host;
        this.port = port;
        this.basePath=basePath;
        this.directory=directory;
    }

    /**
     * 构造基于秘钥认证的sftp对象
     */
    public SFTPUtil(String username, String host, int port, String privateKey) {
        this.username = username;
        this.host = host;
        this.port = port;
        this.privateKey = privateKey;
    }

    public SFTPUtil(){}


    /**
     * 连接sftp服务器
     */
    public void login(){
        try {
            JSch jsch = new JSch();
            if (privateKey != null) {
                jsch.addIdentity(privateKey);// 设置私钥  
            }

            session = jsch.getSession(username, host, port);

            if (password != null) {
                session.setPassword(password);
            }
            Properties config = new Properties();
            config.put("StrictHostKeyChecking", "no");

            session.setConfig(config);
            session.connect();

            Channel channel = session.openChannel("sftp");
            channel.connect();

            sftp = (ChannelSftp) channel;
        } catch (JSchException e) {
            e.printStackTrace();
        }
    }

    /**
     * 关闭连接 server
     */
    public void logout(){
        if (sftp != null&&sftp.isConnected()) {
                sftp.disconnect();
        }
        if (session != null&&session.isConnected()) {
                session.disconnect();
            }
    }

    /***从ftp服务器上下载图片压缩成zip包 写出
     * @Description:
     * @Param: [basePath, directory, list, type, sos]
     * @return: java.util.List<java.io.File>
     * @author: yangsx
     * @create: 2019/1/15 8:54
     */

    public List<File> downloadFiles(String imgPath,String basePath, String directory, List<EmplUserImag> list, String type, ServletOutputStream sos) throws SftpException, FileNotFoundException{
        File file = new File(imgPath);//"C:\\Users\\imgDownload\\temporary"
        String path = basePath+directory+"/";
        if(!file.exists()){
            file.mkdirs();
        }
        List<File> idCardFiles = new ArrayList<>();
        if (directory != null && !"".equals(directory)) {
            sftp.cd(basePath+directory);
        }
        if(!list.isEmpty()){
            if(type.equals("noUserPhoto")){
                for (EmplUserImag emplUserImag : list) {
                    try {
                        //户口首页图片
                        download( path,emplUserImag.getResidenceStart(),file+"\\"+emplUserImag.getResidenceStart());
                        idCardFiles.add(new File(file+"\\"+emplUserImag.getResidenceStart()));
                        //户口本人图片
                        download( path,emplUserImag.getResidenceUser(),file+"\\"+emplUserImag.getResidenceUser());
                        idCardFiles.add(new File(file+"\\"+emplUserImag.getResidenceUser()));
                        //身份证正面
                        download( path,emplUserImag.getCardPositive(),file+"\\"+emplUserImag.getCardPositive());
                        idCardFiles.add(new File(file+"\\"+emplUserImag.getCardPositive()));
                        //身份证反面
                        download( path,emplUserImag.getCardOther(),file+"\\"+emplUserImag.getCardOther());
                        idCardFiles.add(new File(file+"\\"+emplUserImag.getCardOther()));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                try {
                    ZipUtils.toZip(idCardFiles, sos);
                    file.delete();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
            if(type.equals("userPhoto")){
                //用户一寸照
                for (EmplUserImag emplUserImag : list) {
                    //用户一寸照
                    try {
                        download( path,emplUserImag.getUserPhoto(),file+"\\"+emplUserImag.getUserPhoto());
                        idCardFiles.add(new File(file+"\\"+emplUserImag.getUserPhoto()));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                try {
                    ZipUtils.toZip(idCardFiles, sos);
                    file.delete();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
        }
        return idCardFiles;
    }

    /**
     * 下载文件。
     * @param directory 下载目录
     * @param downloadFile 下载的文件
     * @param saveFile 存在本地的路径
     */
    public void download(String directory, String downloadFile, String saveFile) throws SftpException, FileNotFoundException{
        if (directory != null && !"".equals(directory)) {
            sftp.cd(directory);
        }
        File file = new File(saveFile);
        sftp.get(downloadFile, new FileOutputStream(file));
    }

    /**
     * 将输入流的数据上传到sftp作为文件。文件完整路径=basePath+directory
     * @param basePath  服务器的基础路径
     * @param directory  上传到该目录
     * @param sftpFileName  sftp端文件名
     * @param in   输入流
     */
    public void upload(String basePath,String directory, String sftpFileName, InputStream input) throws SftpException{
        try {
            sftp.cd(basePath);
            sftp.cd(directory);
        } catch (SftpException e) {
            //目录不存在,则创建文件夹
            String [] dirs=directory.split("/");
            String tempPath=basePath;
            for(String dir:dirs){
               if(null== dir || "".equals(dir)) continue;
               tempPath+="/"+dir;
               try{
                  sftp.cd(tempPath);
               }catch(SftpException ex){
                  sftp.mkdir(tempPath);
                  sftp.cd(tempPath);
               }
            }
        }
        sftp.put(input, sftpFileName);  //上传文件
    }


        /**
         * 下载文件
         * @param directory 下载目录
         * @param downloadFile 下载的文件名
         * @return 字节数组
         */
    public byte[] download(String directory, String downloadFile) throws SftpException, IOException{
        if (directory != null && !"".equals(directory)) {
            sftp.cd(directory);
        }
        InputStream is = sftp.get(downloadFile);

        byte[] fileData = IOUtils.toByteArray(is);

        return fileData;
    }


    /**
     * 删除文件
     * @param directory 要删除文件所在目录
     * @param deleteFile 要删除的文件
     */
    public void delete(String directory, String deleteFile) throws SftpException{
        sftp.cd(directory);
        sftp.rm(deleteFile);
    }


    /**
     * 列出目录下的文件
     * @param directory 要列出的目录
     * @param
     */
    public Vector<?> listFiles(String directory) throws SftpException {
        return sftp.ls(directory);
    }

}

zip 导出工具类:

package com.unicom.sh.pom.file.util;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;


/***
 * @Description:
 * @Param:
 * @return:
 * @author: 杨舜玺
 * @create: 2019/1/7 16:51
 */
public class ZipUtils {

    private static final int  BUFFER_SIZE = 2 * 1024;

    private static final Logger logger = LoggerFactory.getLogger(ZipUtils.class);

    private ZipUtils() {
        logger.info("初始化成功");
    }

    /**
     * 压缩成ZIP 方法2
     * @param srcFiles 需要压缩的文件列表
     * @param out           压缩文件输出流
     * @throws RuntimeException 压缩失败会抛出运行时异常
     */
    public static void toZip(List<File> srcFiles , OutputStream out)throws IOException {
        try(ZipOutputStream zos = new ZipOutputStream(out)){
            for (File srcFile : srcFiles) {
                    byte[] buf = new byte[BUFFER_SIZE];
                    zos.putNextEntry(new ZipEntry(srcFile.getName()));
                    int len;
                try (FileInputStream in = new FileInputStream(srcFile)){
                    while ((len = in.read(buf)) != -1) {
                        zos.write(buf, 0, len);
                    }
                }
            }
        } catch (IOException e) {
            logger.info("io异常");
            throw new IOException("zip error from ZipUtils",e);
        }
    }

}

完成

猜你喜欢

转载自blog.csdn.net/qq_39930369/article/details/86568778