• java+freemarker+word 生成转换doc文档


    首先需要导入jar  引入包

    maven 引入greemarker模板

    <!-- freemarker jar -->
    <dependency>
         <groupId>org.freemarker</groupId>
         <artifactId>freemarker</artifactId>
         <version>2.3.20</version>
    </dependency>

    这是java 类型的引用 别弄错

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

    下面是java代码

    //用于返回一个临时模板
    public Template getTemplate(String filename) {
    //Configuration用于读取ftl文件 Configuration configuration = new Configuration(); configuration.setDefaultEncoding("utf-8"); /*以下是两种指定ftl文件所在目录路径的方式, 注意这两种方式都是 * 指定ftl文件所在目录的路径,而不是ftl文件的路径 */ //指定路径的第一种方式(根据某个类的相对路径指定) // configuration.setClassForTemplateLoading(WordExportUtils.class,""); //指定路径 String templateFolder = WordExportHelper.class.getClassLoader().getResource("../../").getPath() + "bizmodules/templates/generatedoc/"; Template t = null; try { configuration.setDirectoryForTemplateLoading(new File(templateFolder)); //以utf-8的编码读取ftl文件 String filePath = ""; String targetPath = ""; String ftlfileName = ""; ftlfileName = UUIDUtil.getUUID() + filename; filePath = templateFolder + filename; targetPath = templateFolder + ftlfileName;
            //这里是将文件复制到临时模板中 WordExportHelper.fileCopy_channel(filePath, targetPath);
            //设置格式 t
    = configuration.getTemplate(ftlfileName, "utf-8");
            //删除多余的ftl WordExportHelper.deleteFile(targetPath); }
    catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return t; }

    调用时候

    //返回template模板
    Template t=inviteBidsManager.getTemplate(ftl);
    //要替换的参数 map Map map
    =inviteBidsManager.generateDoc(inMap);
    HttpServletResponse response = (HttpServletResponse) inMap.get(CommonAttribute.HTTP_RESPONSE);
    String fileName ="导出word文档的名字";
    try {
        //下载文件
    DocGenerateHelper.generateDocWithDownload(map,t, fileName,response);
    } catch (Exception e) {
    e.printStackTrace();
    }

    下面是WordExportHelper帮助类

    package com.csnt.scdp.bizmodules.helper;
    
    import freemarker.template.Configuration;
    import freemarker.template.Template;
    import freemarker.template.TemplateException;
    import org.apache.commons.io.IOUtils;
    import sun.misc.BASE64Encoder;
    
    import javax.servlet.ServletOutputStream;
    import javax.servlet.http.HttpServletResponse;
    import java.io.*;
    import java.net.URLEncoder;
    import java.nio.channels.FileChannel;
    import java.util.Map;
    
    /**
     * Created by yuany on 2018/3/19.
     */
    public class WordExportHelper {
        public static void WordExport(HttpServletResponse response, Map dataMap) throws IOException{
    
            String eventId=(String) dataMap.get("eventId");
    
            //Configuration用于读取ftl文件
            Configuration configuration = new Configuration();
            configuration.setDefaultEncoding("utf-8");
    
          /*以下是两种指定ftl文件所在目录路径的方式, 注意这两种方式都是
           * 指定ftl文件所在目录的路径,而不是ftl文件的路径
           */
    
            //指定路径的第一种方式(根据某个类的相对路径指定)
    
            //指定路径
            String templateFolder = WordExportHelper.class.getClassLoader().getResource("../../").getPath() + "templates/";
            configuration.setDirectoryForTemplateLoading(new File(templateFolder));
            // 输出文档路径及名称
            File outFile = new File(eventId+".doc");
    
            //以utf-8的编码读取ftl文件
            Template t = null;
            t = configuration.getTemplate("IllegalTemplate.ftl","utf-8");
            Writer out = null;
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"),10240);
            try {
                t.process(dataMap, out);
            } catch (TemplateException e) {
                e.printStackTrace();
            }
            out.close();
    
            InputStream fin = null;
            ServletOutputStream download = null;
            try {
                fin = new FileInputStream(outFile);
                response.setCharacterEncoding("utf-8");
                response.setContentType("application/octet-stream");
                // 设置浏览器以下载的方式处理该文件名
                String FileName = eventId+".doc";
                response.setHeader("Content-Disposition", "attachment;filename=".concat(String.valueOf(URLEncoder.encode(FileName, "UTF-8"))));
                download=response.getOutputStream();
    //            byte[] buffer = new byte[512];  // 缓冲区
    //            int bytesToRead = -1;
    //            // 通过循环将读入的Word文件的内容输出到浏览器中
    //            while((bytesToRead = fin.read(buffer)) != -1) {
    //                download.write(buffer, 0, bytesToRead);
    //            }
                IOUtils.copy(fin, download);
                download.flush();
                fin.close();
            }finally {
                if(fin != null) fin.close();
                if(download != null) download.close();
                if(outFile != null) outFile.delete(); // 删除临时文件
            }
        }
    
    
        public static String getImageStr(String str) {
    
            InputStream in = null;
            byte[] data = null;
            try {
                in = new FileInputStream(str);
                data = new byte[in.available()];
                in.read(data);
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            BASE64Encoder encoder = new BASE64Encoder();
            return encoder.encode(data);
        }
    
    
    
        public static void fileCopy_channel(String filePath,String targetPath) {
            FileChannel input = null;
            FileChannel output = null;
            try {
                input = new FileInputStream(filePath).getChannel();
                output = new FileOutputStream(targetPath).getChannel();
                output.transferFrom(input, 0, input.size());
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if (input != null) {
                        input.close();
                    }
                    if (output != null) {
                        output.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    
        public static void deleteFile(String fileName) {
            File file = new File(fileName);
            if (file.exists()) {
                file.delete();
            }
        }
    
    }

    DocGenerateHelper类

    package com.csnt.scdp.bizmodules.helper;
    
    import com.csnt.scdp.framework.helper.IOHelper;
    import com.csnt.scdp.framework.util.UUIDUtil;
    import freemarker.template.Template;
    import org.apache.struts2.ServletActionContext;
    
    import javax.servlet.http.HttpServletResponse;
    import java.io.*;
    import java.net.URLEncoder;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.Map;
    
    /**
     * Created by weixiao on 2018/9/6.
     */
    public class DocGenerateHelper {
    
    
        public static String genDoc(Map outMap, Template t, String clientFileName) throws Exception {
            SimpleDateFormat df = new SimpleDateFormat("MMddHHmmss");
            String tempFileName = IOHelper.checkPath(System.getProperty("java.io.tmpdir")) + "docgenerate" + File.separator + df.format(new Date()) + File.separator + clientFileName + ".doc";
            File file = new File(tempFileName);
            File fileParent = file.getParentFile();
            //首先创建父类文件夹
            if (!fileParent.exists()) {
                fileParent.mkdirs();
            }
            file.createNewFile();
            Writer out = null;
            try {
                IOHelper.generateEmptyDic(tempFileName, false);
                out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(tempFileName), "utf-8"), 10240);
                t.process(outMap, out);
            } finally {
    
                out.flush();
                out.close();
            }
            return tempFileName;
        }
    
        //通过文件输入输出流下载word
        //设置向浏览器端传送的文件格式
        public static void generateDocWithDownload(Map outMap, Template t, String clientFileName,HttpServletResponse response) throws Exception {
            if (clientFileName == null || clientFileName == "") {
                clientFileName = UUIDUtil.getUUID();
            }
            String fileName = genDoc(outMap, t, clientFileName);
            response.reset();
    
            InputStream fis = null;
            OutputStream toClient = null;
            File outFile = new File(fileName);
            try {
                fis = new BufferedInputStream(new FileInputStream(outFile));
                byte[] buffer = new byte[fis.available()];
                fis.read(buffer);
                fis.close();
                // 清空response
                response.reset();
                // 设置response的Header
                clientFileName = URLEncoder.encode(clientFileName + ".doc", "utf-8");                                  //这里要用URLEncoder转下才能正确显示中文名称
                response.addHeader("Content-Disposition", "attachment;filename=" + clientFileName);
                response.addHeader("Content-Length", "" + outFile.length());
                toClient = new BufferedOutputStream(response.getOutputStream());
                response.setContentType("application/octet-stream");
                toClient.write(buffer);
                toClient.flush();
    
                fis.close();
                toClient.close();
            } finally {
                WordExportHelper.deleteFile(fileName);
                String directory=fileName.substring(0,fileName.lastIndexOf("\"));
                WordExportHelper.deleteFile(directory);
                if (fis != null) {
                    fis.close();
                }
                if (toClient != null) {
                    toClient.close();
                }
            }
        }
    
        //通过文件输入输出流下载word
        //设置向浏览器端传送的文件格式
        public static void generateDocDownload(String path,String clientFileName,HttpServletResponse response) throws Exception {
            if (clientFileName == null || clientFileName == "") {
                clientFileName = UUIDUtil.getUUID();
            }
    //        String fileName=genDoc(clientFileName);
            response.reset();
            InputStream fis = null;
            OutputStream toClient = null;
            File outFile = new File(path);
            try {
                fis = new BufferedInputStream(new FileInputStream(outFile));
                byte[] buffer = new byte[fis.available()];
                fis.read(buffer);
                fis.close();
    
                // 清空response
                response.reset();
                // 设置response的Header
    //            clientFileName = URLEncoder.encode(clientFileName + ".doc", "utf-8");                                  //这里要用URLEncoder转下才能正确显示中文名称
                response.addHeader("Content-Disposition", "attachment;filename=" + clientFileName);
                response.addHeader("Content-Length", "" + outFile.length());
                toClient = new BufferedOutputStream(response.getOutputStream());
                response.setContentType("application/octet-stream");
                toClient.flush();
    
                fis.close();
                toClient.close();
            } finally {
                if (fis != null) {
                    fis.close();
                }
                if (toClient != null) {
                    toClient.close();
                }
            }
        }
        public static String genDoc(String clientFileName) throws Exception {
            SimpleDateFormat df = new SimpleDateFormat("MMddHHmmss");
            String tempFileName = IOHelper.checkPath(System.getProperty("java.io.tmpdir")) + "docgenerate" + File.separator + df.format(new Date()) + File.separator + clientFileName + ".doc";
            File file = new File(tempFileName);
            File fileParent = file.getParentFile();
            //首先创建父类文件夹
            if (!fileParent.exists()) {
                fileParent.mkdirs();
            }
            file.createNewFile();
            Writer out = null;
            try {
                IOHelper.generateEmptyDic(tempFileName, false);
                out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(tempFileName), "utf-8"), 10240);
    
            } finally {
    
                out.flush();
                out.close();
            }
            return tempFileName;
        }
    
    
        public static String generateDocWithDownload_temp(Map outMap, Template t, String clientFileName) throws Exception {
            String fileUrl = "";
            if (clientFileName == null || clientFileName == "") {
                clientFileName = UUIDUtil.getUUID();
            }
            String fileName = genDoc(outMap, t, clientFileName);
            HttpServletResponse response = ServletActionContext.getResponse();
            response.reset();
    
            InputStream fis = null;
            OutputStream toClient = null;
            File outFile = new File(fileName);
            try {
                fis = new BufferedInputStream(new FileInputStream(outFile));
                byte[] buffer = new byte[fis.available()];
                fis.read(buffer);
                fis.close();
                // 清空response
                response.reset();
                // 设置response的Header
                clientFileName = URLEncoder.encode(clientFileName + ".doc", "utf-8");                                  //这里要用URLEncoder转下才能正确显示中文名称
                response.addHeader("Content-Disposition", "attachment;filename=" + clientFileName);
                response.addHeader("Content-Length", "" + outFile.length());
                toClient = new BufferedOutputStream(response.getOutputStream());
                response.setContentType("application/octet-stream");
                toClient.write(buffer);
                toClient.flush();
                fileUrl = outFile.toString();
    
                fis.close();
                toClient.close();
            } finally {
                if (fis != null) {
                    fis.close();
                }
                if (toClient != null) {
                    toClient.close();
                }
    
            }
            return fileUrl;
        }
    }
  • 相关阅读:
    JavaScript常用单词整理总结
    花了100多去KTV不是唱歌,竟然是……
    当你左右看看没有发现我时,千万千万别往看……
    winform分页案例简单实现方式~
    来自一位家长的肺腑之言,句句在理!!!
    “小朋友”们节日快乐呀~
    你在学校我安排了你没有做到最多凶你一顿,在公司不一样,直接得让走人!...
    你也可以做一个简易抽奖程序!
    不好意思,你这个加分理由不行……
    【RocketMQ】客户端源码解析
  • 原文地址:https://www.cnblogs.com/wcnwcn/p/13426073.html
Copyright © 2020-2023  润新知