美文网首页
freemarker模板生成word

freemarker模板生成word

作者: 勇往直前z | 来源:发表于2019-01-09 15:51 被阅读0次

    最近做的招聘小程序,要在后台生成word简历,做了个demo简单记录一下。

    word模板

    先找一个word简历模板,另存为Word 2003 XML文档,然后用文本编辑器打开


    TIM截图20190109154619.png

    替换对应的字段名称,例如:jobStatus --> ${jobStatus},保存。然后在项目用创建一个freemarker模板,将整个XML复制过去。


    TIM截图20190109154447.png
    模板完成。

    依赖

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-freemarker</artifactId>
    </dependency>
    

    核心代码

    package com.hlhlo.web.admin.service.impl;
    
    import com.hlhlo.cloud.api.job.dto.CareerObjectiveDto;
    import com.hlhlo.cloud.api.job.dto.EducationDto;
    import com.hlhlo.cloud.api.job.dto.ResumeDto;
    import com.hlhlo.cloud.api.job.dto.WorkExperienceDto;
    import com.hlhlo.cloud.api.job.entity.Projects;
    import com.hlhlo.cloud.api.job.mapper.ResumeMapper;
    import com.hlhlo.web.admin.service.ResumeService;
    import freemarker.template.Configuration;
    import freemarker.template.Template;
    import org.apache.commons.lang3.StringUtils;
    import org.apache.commons.lang3.time.DateFormatUtils;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    import javax.servlet.ServletOutputStream;
    import javax.servlet.http.Cookie;
    import javax.servlet.http.HttpServletResponse;
    import java.io.*;
    import java.util.*;
    
    @Service(value = "adminResumeService")
    public class ResumeServiceImpl implements ResumeService {
    
        @Autowired
        private ResumeMapper resumeMapper;
    
        @Override
        public void downloadResume(Long userId, HttpServletResponse response) {
            ResumeDto resumeDto = resumeMapper.findUserResume(userId);
            Configuration configuration = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
            configuration.setDefaultEncoding("UTF-8");
            Map<String,Object> dataMap = new HashMap<>();
            dataMap.put("name", ifNull(resumeDto.getRealName()));
            dataMap.put("sex", ifNull(resumeDto.getSex()));
            dataMap.put("jobStatus", ifNull(resumeDto.getJobStatus()));
            dataMap.put("mobile", ifNull(resumeDto.getMobile()));
            if (resumeDto.getBirthday() != null) {
                dataMap.put("birthday", ifNull(DateFormatUtils.format(resumeDto.getBirthday(), "yyyy-MM-dd")));
            } else {
                dataMap.put("birthday", "");
            }
            dataMap.put("email", ifNull(resumeDto.getEmail()));
            if (resumeDto.getStartWorkTime() != null) {
                dataMap.put("startWorkTime", ifNull(DateFormatUtils.format(resumeDto.getStartWorkTime(), "yyyy-MM-dd")));
            } else {
                dataMap.put("startWorkTime", "");
            }
            dataMap.put("city", ifNull(resumeDto.getCity()));
            dataMap.put("info", ifNull(resumeDto.getInfo()));
    
            List<Map<String,Object>> cos = new ArrayList<>();
            List<Map<String,Object>> edus = new ArrayList<>();
            List<Map<String,Object>> wes = new ArrayList<>();
            List<Map<String,Object>> ps = new ArrayList<>();
            List<CareerObjectiveDto> careerObjectives = resumeDto.getCareerObjectives();
            if (careerObjectives != null && !careerObjectives.isEmpty()) {
                for (CareerObjectiveDto co: careerObjectives) {
                    Map<String,Object> map = new HashMap<>();
                    map.put("function", ifNull(co.getFunction()));
                    map.put("salary", ifNull(co.getSalary()));
                    map.put("location", ifNull(co.getLocation()));
                    map.put("industry", ifNull(co.getIndustry()));
                    cos.add(map);
                }
            }
            dataMap.put("cos", cos);
            List<EducationDto> educations = resumeDto.getEducations();
            if (educations != null && !educations.isEmpty()) {
                for (EducationDto e: educations) {
                    Map<String,Object> map = new HashMap<>();
                    if (e.getStartDate() != null) {
                        map.put("startDate", ifNull(DateFormatUtils.format(e.getStartDate(), "yyyy")));
                    } else {
                        map.put("startDate", "");
                    }
                    if (e.getEndDate() != null) {
                        map.put("endDate", ifNull(DateFormatUtils.format(e.getEndDate(), "yyyy")));
                    } else {
                        map.put("endDate", "");
                    }
                    map.put("school", ifNull(e.getSchool()));
                    map.put("major", ifNull(e.getMajor()));
                    map.put("degree", ifNull(e.getDegree()));
                    map.put("schoolExp", ifNull(e.getSchoolExp()));
                    edus.add(map);
                }
            }
            dataMap.put("edus", edus);
            List<WorkExperienceDto> workExperiences = resumeDto.getWorkExperiences();
            if (workExperiences != null && !workExperiences.isEmpty()) {
                for (WorkExperienceDto we: workExperiences) {
                    Map<String,Object> map = new HashMap<>();
                    if (we.getStartDate() != null) {
                        map.put("startDate", ifNull(DateFormatUtils.format(we.getStartDate(), "yyyy-MM")));
                    } else {
                        map.put("startDate", "");
                    }
                    if (we.getEndDate() != null) {
                        map.put("endDate", ifNull(DateFormatUtils.format(we.getEndDate(), "yyyy-MM")));
                    } else {
                        map.put("endDate", "");
                    }
                    map.put("companyName", ifNull(we.getCompanyName()));
                    map.put("position", ifNull(we.getPosition()));
                    map.put("jobExp", ifNull(we.getJobExp()));
                    wes.add(map);
                }
            }
            dataMap.put("wes", wes);
            List<Projects> projects = resumeDto.getProjects();
            if (projects != null && !projects.isEmpty()) {
                for (Projects p: projects) {
                    Map<String,Object> map = new HashMap<>();
                    map.put("projectName", ifNull(p.getProjectName()));
                    if (p.getStartDate() != null) {
                        map.put("startDate", ifNull(DateFormatUtils.format(p.getStartDate(), "yyyy-MM")));
                    } else {
                        map.put("startDate", "");
                    }
                    if (p.getEndDate() != null) {
                        map.put("endDate", ifNull(DateFormatUtils.format(p.getEndDate(), "yyyy-MM")));
                    } else {
                        map.put("endDate", "");
                    }
                    map.put("projectRole", ifNull(p.getProjectRole()));
                    map.put("projectExp", ifNull(p.getProjectExp()));
                    ps.add(map);
                }
            }
            dataMap.put("ps", ps);
            configuration.setClassForTemplateLoading(this.getClass(), "/templates");//模板文件所在路径
            Template t = null;
            try {
                t = configuration.getTemplate("jianli.ftl"); //获取模板文件
            } catch (IOException e) {
                e.printStackTrace();
            }
            File outFile = new File(resumeDto.getRealName() +"的简历" + UUID.randomUUID() + ".doc"); //导出文件
            Writer out = null;
            try {
                out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile)));
                t.process(dataMap, out); //将填充数据填入模板文件并输出到目标文件
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (out != null) {
                    try {
                        out.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            try(InputStream inputStream = new FileInputStream(outFile);ServletOutputStream outputStream = response.getOutputStream()) {
                response.setCharacterEncoding("utf-8");
                response.setContentType("application/msword");
                String fileName = outFile.getName();
                fileName = response.encodeURL(new String(fileName.getBytes("gb2312"), "iso8859-1"));
                response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
                //创建Cookie并添加到response中
                Cookie cookie = new Cookie("fileDownload", "true");
                cookie.setPath("/");
                response.addCookie(cookie);
                byte[] buffer = new byte[512];  // 缓冲区
                int bytesToRead = -1;
                // 通过循环将读入的Word文件的内容输出到浏览器中
                while((bytesToRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesToRead);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                outFile.delete();
            }
        }
    
        private String ifNull(String content) {
            return StringUtils.isNotBlank(content) ? content : "";
        }
    }
    

    相关文章

      网友评论

          本文标题:freemarker模板生成word

          本文链接:https://www.haomeiwen.com/subject/dnlgrqtx.html