SpringBoot+freemaker实现word导出功能

使用SpringBoot+freemaker实现word导出功能

1、引入pom依赖
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
2、加入工具类
package com.jt.www.util.mail;

import freemarker.template.Configuration;
import freemarker.template.Template;

import java.io.*;
import java.util.Map;

/**
 * @Description:   生成Word工具类
 * @author: xuxinku
 * @Date: 2019/6/16 9:42
 * @ModifiedDate:
 * @Copyright:XX保险股份有限公司
 */
public class WordUtil {

    /**
     * @Desc:生成word文件
     * @Author:xuxinke
     * @Date:2019/6/16 9:42
     * @param dataMap word中需要展示的动态数据,用map集合来保存
     * @param templateName word模板名称,例如:06test.ftl
     * @param filePath 文件生成的目标路径,例如:D:/wordFile/
     * @param fileName 生成的文件名称,例如:test.doc
     */
    @SuppressWarnings("unchecked")
    public static String createWord(Map dataMap, String templateName, String filePath, String fileName){
        try {
            //创建配置实例
            Configuration configuration = new Configuration(Configuration.VERSION_2_3_23);

            //设置编码
            configuration.setDefaultEncoding("UTF-8");

            //ftl模板文件统一放至 com.lun.template 包下面
            //  D:\ideas\JTJBW\edu-svc\src\main\resources\templates
            configuration.setClassForTemplateLoading(WordUtil.class,"/");

            //获取模板
            Template template = configuration.getTemplate(templateName);

            //输出文件
            File outFile = new File(filePath+ File.separator+fileName);

            //如果输出目标文件夹不存在,则创建
            if (!outFile.getParentFile().exists()){
                outFile.getParentFile().mkdirs();
            }

            //将模板和数据模型合并生成文件
            Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile),"UTF-8"));

            //生成文件
            template.process(dataMap, out);

            //关闭流
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        String WJ=filePath+fileName;
        return WJ;
    }
}






3、创建ftl模板文件
3.1创建Word文件定义好变量保存为xml格式

在这里插入图片描述
在这里插入图片描述

3.2重命名为.ftl文件

在这里插入图片描述

4.调用工具类生成word文件
4.1 导出word功能
@GetMapping("wordTest")
    public String wordTest(){

        /** 用于组装word页面需要的数据 */
        Map<String, String> dataMap = new HashMap<String, String>();

        dataMap.put("post_name","Java开发工程师");
        dataMap.put("adjustment","是");
        dataMap.put("name","小张");
        dataMap.put("sex","男");
        dataMap.put("nation","汉族");
        dataMap.put("height","172cm");
        dataMap.put("zzmm","共青团员");
        dataMap.put("native_place","福建省南平市");
        dataMap.put("marriage","未婚");
        dataMap.put("sfjhm","1313154564684684234");
        dataMap.put("birth","1999-01-20");
        dataMap.put("title","高级Java开发工程师");
        dataMap.put("title_time","2023-03-15");
        dataMap.put("phone","13629538953");
        dataMap.put("email","227154@qq.com");
        dataMap.put("school_time","2021-06-01");
        dataMap.put("school","厦门工学院");
        dataMap.put("most_academic","本科");
        dataMap.put("chat_address","xx省xx市xxx");
        dataMap.put("foreign","CET4");
        dataMap.put("computer","4级");
        dataMap.put("specialty","篮球");
        dataMap.put("now_salary","6000");
        dataMap.put("except_salary","8000");
        dataMap.put("xxsource","boss直聘");

        //String filePath = "D:/JB/";
        //String filePath =System.getProperty("java.io.tmpdir")+ File.separator;
        String filePath = "E:\\";

        System.out.println("查看临时路径=======》"+filePath);
        //文件唯一名称
        String fileOnlyName = "ccc.doc";
        /** 生成word  数据包装,模板名,文件生成路径,生成的文件名*/
        String WJ = WordUtil.createWord(dataMap, "c.ftl", filePath, fileOnlyName);

        return WJ;
    }
4.2 下载word功能
/**
     * 平台实现更新包下载
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/download")
    public String downloadFile(HttpServletRequest request,
                               HttpServletResponse response, String fileFullName) throws UnsupportedEncodingException {
//        String rootPath = propertiesconfig.getUploadpacketPath();//这里是我在配置文件里面配置的根路径,各位可以更换成自己的路径之后再使用(例如:D:/test)
        String rootPath = "E://";
        String FullPath = rootPath + fileFullName;//将文件的统一储存路径和文件名拼接得到文件全路径
        File packetFile = new File(FullPath);
        String fileName = packetFile.getName(); //下载的文件名
        File file = new File(FullPath);
        // 如果文件名存在,则进行下载
        if (file.exists()) {
            // 配置文件下载
            response.setHeader("content-type", "application/octet-stream");
            response.setContentType("application/octet-stream");
            // 下载文件能正常显示中文
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            // 实现文件下载
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                OutputStream os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
                System.out.println("Download the song successfully!");
            } catch (Exception e) {
                System.out.println("Download the song failed!");
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        } else {//对应文件不存在
            try {
                //设置响应的数据类型是html文本,并且告知浏览器,使用UTF-8 来编码。
                response.setContentType("text/html;charset=UTF-8");

                //String这个类里面, getBytes()方法使用的码表,是UTF-8,  跟tomcat的默认码表没关系。 tomcat iso-8859-1
                String csn = Charset.defaultCharset().name();

                System.out.println("默认的String里面的getBytes方法使用的码表是: " + csn);

                //1. 指定浏览器看这份数据使用的码表
                response.setHeader("Content-Type", "text/html;charset=UTF-8");
                OutputStream os = response.getOutputStream();

                os.write("对应文件不存在".getBytes());
            } catch (IOException e) {
                e.printStackTrace();
            }
//                return R.error("-1","对应文件不存在");
        }
        return null;
    }
5、效果展示

在这里插入图片描述
ps:有个需要注意的地方, 由于freemarker的是用xml来生成的Word , 导致很多手机软件打开是乱码的 ,手机软件不能识别 xml格式的文档, 这个我也很头疼, 有能解决的大神可以私信或者评论下 互相学习。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot + Freemarker 会自动跳转到 login 页的原因可能是因为你的应用程序中使用了 Spring Security,而 Spring Security 会默认开启登录验证功能。 如果你想要禁用 Spring Security 的登录验证功能,可以在 application.properties 或 application.yml 文件中添加以下配置: ``` spring.security.enabled=false ``` 如果你想要保留 Spring Security 的登录验证功能,可以在你的应用程序中添加一个自定义的登录页面,并将 Spring Security 的登录页面指向你的自定义登录页面。你可以按照以下步骤进行操作: 1. 创建一个自定义的登录页面。比如,你可以将登录页面的文件名设置为 "custom-login.html",并将其放置在 "/templates/" 目录下。 ``` <!DOCTYPE html> <html> <head> <title>Login Page</title> </head> <body> <h2>Login Page</h2> <form action="/login" method="POST"> <label for="username">Username:</label> <input type="text" id="username" name="username"><br><br> <label for="password">Password:</label> <input type="password" id="password" name="password"><br><br> <input type="submit" value="Submit"> </form> </body> </html> ``` 2. 创建一个 Spring Security 的配置类,并在配置类中将登录页面指向你的自定义登录页面。 ``` @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .anyRequest().authenticated() .and() .formLogin() .loginPage("/custom-login.html") .permitAll(); } } ``` 这样,当用户访问需要登录验证的页面时,Spring Security 就会自动跳转到你的自定义登录页面。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值