美文网首页
word生成工具类

word生成工具类

作者: 咖啡机an | 来源:发表于2019-01-11 10:47 被阅读0次

    1.创建word模板,注意兼容性

    建议使用office的word创建doc文件,并且将word另存为2003的xml文件。将xml文件中需要替换的内容使用${}替换,{}内为map的key。若需要插入图片,需要先在word模板中插入图片,转成xml模板后把图片的base64码替换。

    2.根据模板导出word工具类

    import freemarker.template.Configuration;
    import freemarker.template.Template;
    import org.springframework.web.context.ContextLoader;
    
    import javax.servlet.http.HttpServletRequest;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.OutputStreamWriter;
    import java.io.Writer;
    import java.util.Map;
    
    /**
     * 使用模板导出word
     *
     * @author archie Lin
     * @date 2018-11-13
     */
    public class WordUtils {
    
        public static String exportMillCertificateWord(HttpServletRequest request, Map map,
                                                       String title, String ftlFile) throws IOException {
            String templateFolder =
                    ContextLoader.getCurrentWebApplicationContext().getServletContext().getRealPath("/") + CommonConstant.FILE_FOLDER;
            //文件的名称
            String absoluteStrFilePath = request.getServletContext().getRealPath("/").replace("rest", "web") +
                    CommonConstant.FILE_TEMP_FOLDER;
            Configuration configuration = null;
            configuration = new Configuration();
            configuration.setDefaultEncoding("utf-8");
            try {
                configuration.setDirectoryForTemplateLoading(new File(templateFolder));
            } catch (IOException e) {
                e.printStackTrace();
            }
            Template freemarkerTemplate = configuration.getTemplate(ftlFile);
            File filePath = new File(absoluteStrFilePath);
            if (!CommonMethod.isHasFolder(filePath)) {
                CommonMethod.createFolder(filePath);
            }
            //文件的路径
            StringBuffer fileUrl = new StringBuffer();
            String fileName = title + TimeUtils.getTimeStamp() + ".doc";
            fileUrl.append(absoluteStrFilePath);
            fileUrl.append(fileName);
            String fileUrlStr = fileUrl.toString();
            File file = null;
            FileInputStream fin = null;
            FileOutputStream fileOutputStream = null;
            try {
                // 调用工具类的createDoc方法生成Word文档
                file = createDoc(map, freemarkerTemplate, templateFolder);
                fin = new FileInputStream(file);
                fileOutputStream = new FileOutputStream(new File(fileUrlStr));
                byte[] buffer = new byte[512];
                int bytesToRead = -1;
                while ((bytesToRead = fin.read(buffer)) != -1) {
                    fileOutputStream.write(buffer, 0, bytesToRead);
                }
            } finally {
                if (fin != null) {
                    fin.close();
                }
                if (fileOutputStream != null) {
                    fileOutputStream.close();
                }
                if (file != null) {
                    file.delete();
                }
            }
            return fileName;
        }
    
        private static File createDoc(Map<?, ?> dataMap, Template template, String templateFolder) {
            String name = "temp" + TimeUtils.currTime7() + ".doc";
            File f = new File(templateFolder + name);
            Template t = template;
            try {
                Writer w = new OutputStreamWriter(new FileOutputStream(f), "utf-8");
                t.process(dataMap, w);
                w.close();
            } catch (Exception ex) {
                ex.printStackTrace();
                throw new RuntimeException(ex);
            }
            return f;
        }
    }
    

    相关文章

      网友评论

          本文标题:word生成工具类

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