Freemarker + xml implementation of Java is derived word

Foreword

After recently made a questionnaire derived function, demand is to maintain the subject, answer, export to word, refer to the several options, choose the powerful freemarker + wordxml fixed format after the realization of export capabilities. Export word code is directly reusable, so in this post out, and to sum up, we facilitate away.

Overview of the implementation process

First on the word, adjusting the way you want. Then saved as xml file. Freemarker saved as a template to ftl suffix ending. The need to replace the variable syntax freemarker be replaced. The final data will be ready, and template rendering, to generate the file and return to the browser flow.

Detailed implementation process

Ready word style

We create a new word, we should use Microsoft office, if you use wps may cause some styles are not compatible. In the new office, the set up our table style. Our questionnaire involves four types, radio, multiple choice, fill in the blank, short answer. We make an example of four types.

After the style is no problem, we choose save as word xml 2003 version. It will generate a xml file.

Formatting xml, and replaced with xml syntax freemarker

We can download a tool firstobject xml editor, this can help us see the xml, at the same time help us locate where we need to change.
After copying the past, according to f8 can be formatted, the left is the label right content, we just need to focus w: body can be.

Like the questionnaire on the right of this is a title, we actually rendered when it should be replaced, such as our program data map, the property has a title, we want to show here, we use the syntax $ {title} can .

freemarker concrete syntax, refer to problem freemarker, and here I give a few simple examples.
For example, we would all data is placed in dataList in, so we need to determine, dataList is not empty, empty, we should not be following the logic, not empty, we should first cycle of the title is a must, the answer is the need for the type of again cycle. Grammar reference documentation, not repeat them here.

End program introduced freemarker

<dependency>
    <groupId>org.freemarker</groupId>
    <artifactId>freemarker</artifactId>
</dependency>

Our flt file in the templates in resources.

The back-end code implementation

This code can be multiplexed in a patients gave

public class WordUtils {

    private static Configuration configuration = null;
    private static final String templateFolder = WordUtils.class.getClassLoader().getResource("").getPath()+"/templates/word";
    static {
        configuration = new Configuration();
        configuration.setDefaultEncoding("utf-8");
        try {
            configuration.setDirectoryForTemplateLoading(new File(templateFolder));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     *  @Description:导出word,传入request,response,map就是值,title是导出问卷名,ftl是你要使用的模板名
     */
    public static void exportWord(HttpServletRequest request, HttpServletResponse response, Map map, String title, String ftlFile) throws Exception {
        Template freemarkerTemplate = configuration.getTemplate(ftlFile);
        File file = null;
        InputStream fin = null;
        ServletOutputStream out = null;
        try {
            file = createDocFile(map,freemarkerTemplate);
            fin = new FileInputStream(file);
            String fileName = title + ".doc";
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/msword");
            response.setHeader("Content-Disposition", "attachment;filename="
             +fileName);
            out = response.getOutputStream();
            byte[] buffer = new byte[512];  
            int bytesToRead = -1;
            while((bytesToRead = fin.read(buffer)) != -1) {
                out.write(buffer, 0, bytesToRead);
            }
        }finally {
            if(fin != null) fin.close();
            if(out != null) out.close();
            if(file != null) file.delete(); 
        }
    }

    /**
     *  @Description:创建doc文件
     */
    private static File createDocFile(Map<?, ?> dataMap, Template template) {
        File file = new File("init.doc");
        try {
            Writer writer = new OutputStreamWriter(new FileOutputStream(file), "utf-8");
            template.process(dataMap, writer);
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return file;
    }

}

Once you have tools, we are ready for our map data. map which we can define their own data. Export method call in and then you can utils.

WordUtils.exportWord(request, response, dataMap, "word", "demo.ftl");

Epilogue

So far over, very easy to use, have questions, you can comment exchange.

Guess you like

Origin www.cnblogs.com/jichi/p/11921541.html