Use FreeMarker to export word documents (supports loop export of multiple real-time pictures)

Continuing the update content of the previous issue, the export is a single picture. Just fill in the corresponding placeholder in the src of the path. As the needs change, today we will continue to write a loop to export multiple pictures. Picture into word.

Use FreeMarker to export word documents (supports exporting single pictures)

First we need to set up the corresponding template in word.

After setting, click Save As. The one I am currently using is in html format. There are also many xml formats on the Internet. Each writing method is different.

Then we use Notepad to open it. The first step must be to change the encoding format to utf-8.

Then we put all the tags in the head in the html. If the encoding is not modified and the head tag is not deleted, it will be garbled when exported in the future. This pit is very deep, and it took a long time to solve it.

After all these modifications, we click Save As to change this template to the suffix ftl.

Next we start writing code

 @Override
public void exporttdYsdWord(HttpServletRequest request,
HttpServletResponse response, String objId, String gllx) {
List<Map<String, String>> list = null;
List<Map<String, String>> list3 = null;
List<Map<String, String>> list5 = null;
String ysdName = "";
String ysdSql = "";
String zpSql = "";
String sdsgfa = "";
String ysgjjd = "";
String sdsgfaEname = "";
if ("0".equals(gllx)) {
sdsgfa = "sdsgfa";
ysgjjd = "ysgjjd";
sdsgfaEname = "sczbjys_sczbjys_sdsgfa";
ysdName = "Intermediate Link Acceptance Report";
ysdSql = "select t.gcmc,t.jgdw,t.jgdwfzr,t.jgdwfzrdh,"
+ "t.tdsgdw,t.tdsgdwlxr,t.tdsgdwlxrdh,to_char(t.sqyssj,'yyyy-MM-dd') sqyssj,"
+ "t.czwt, (select a.username from gw_yhgl_user a where a.id = t.yxbzrm) yxbzrm, (select h.value from gw_limit_enums h where h.enumName like '%sczbjys_sczbjys_yxbz%' and h.key = t. yxbz) yxbz,(select t.value from gw_limit_enums t where t.enumName like '%sczbjys_sczbjys_ysgjjd%' and t.key=ysgjjd) ysgjjd from GW_SCZBJYS_ZLC t where t.OBJ_ID = ?";
}
list = this.hibernateDao
.queryForListWithSql(ysdSql,new String[]{objId});

Map<String, String> map0 = new HashMap<String, String>();
Map<String, Object> map = new HashMap<String, Object>();
        StringBuilder sb = new StringBuilder();
        String aa="";
zpSql="select t.ipath ,t.dpt from gw_pig_address_rw t where t.taskid=? and t.ipath is not null and t.dpt='problem photo' and t.dpt is not null and t.ipath not like ' ?t%'" ;
list3 = this.hibernateDao
.queryForListWithSql(zpSql,new String[]{objId});
\t\t\t\t
String zpSqla="select t.ipath ,t.dpt from gw_pig_address_rw t where t.taskid=? and t.ipath is not null and t.dpt is not null and t.ipath not like '?t%'" ;
list5 = this.hibernateDao
.queryForListWithSql(zpSqla,new String[]{objId});
if(list3.size()>0){
\t\t\t\t\t
for (Map<String, String> stringObjectMap : list3) {
if (stringObjectMap.get("DPT").equals("Problem Photo")) {
// map.put("PSZP", "" + PlatformConfigUtil.getString("TASK_PIC_ADDRESS") + stringObjectMap.get("IPATH"));
// aa= String.valueOf(sb.append(PlatformConfigUtil.getString("TASK_PIC_ADDRESS") + stringObjectMap.get("IPATH")).append(","));
// aa= String.valueOf(sb.append(" <img width=249 height=273" src="" + PlatformConfigUtil.getString("TASK_PIC_ADDRESS") + stringObjectMap.get("IPATH")).append( ">").append(","));

aa= String.valueOf(sb.append("<img width="249" height="273" src="" + PlatformConfigUtil.getString("TASK_PIC_ADDRESS") + stringObjectMap.get("IPATH") + "">").append(","));

\t\t                \t

}
}
}else{
\t\t\t\t\t
for (Map<String, String> stringObjectMap : list5) {
if (!stringObjectMap.get("DPT").equals("Problem Photo")) {
// map.put("PSZP", "" + PlatformConfigUtil.getString("TASK_PIC_ADDRESS") + stringObjectMap.get("IPATH"));
// aa= String.valueOf(sb.append(PlatformConfigUtil.getString("TASK_PIC_ADDRESS") + stringObjectMap.get("IPATH")).append(","));
String hh="<img width="249" height="273" src="http://192.168.200.86:18080/XSGL/2023-07-27/20230802155008.jpg",<img width="249" height="273" src="http://192.168.200.86:18080/XSGL/2023-07-27/20230802154952.jpg"";

aa= String.valueOf(sb.append("<img width="249" height="273" src="" + PlatformConfigUtil.getString("TASK_PIC_ADDRESS") + stringObjectMap.get("IPATH") + "">").append(","));


}
}
\t\t\t\t\t
}
\t\t\t\t
if(aa.length()>0){
String a1 = aa.substring(0, aa.length() - 1);
map.put("PSZP", a1);
}else{

if(aa.length()>0){
String a1 = aa.substring(0, aa.length() - 1);
map.put("PSZP", a1);
}else{
map.put("PSZP", "");
}
\t\t\t\t  
}


if (!Tool.isEmptyList(list)) {
map0 = list.get(0);
if (Tool.isEmptyStr(map0.get("gcmc"))) {
map.put("GCMC", "");
} else {
map.put("GCMC", map0.get("gcmc"));
}
if (Tool.isEmptyStr(map0.get("jgdw"))) {
map.put("JGDW", "");
} else {
map.put("JGDW",
getEnumsValueFromEnumDB("sczbjys_sczbjys_jgdw",map0.get("jgdw")));
}

if (Tool.isEmptyStr(map0.get("tdsgdw"))) {
map.put("TDSGDW", "");
} else {
map.put("TDSGDW", map0.get("tdsgdw"));
}
if (Tool.isEmptyStr(map0.get("tdsgdwlxr"))) {
map.put("TDSGDWLXR", "");
} else {
map.put("TDSGDWLXR", map0.get("tdsgdwlxr"));
}
if (Tool.isEmptyStr(map0.get("tdsgdwlxrdh"))) {
map.put("TDSGDWLXRDH", "");
} else {
map.put("TDSGDWLXRDH", map0.get("tdsgdwlxrdh"));
}
if (Tool.isEmptyStr(map0.get("yxbz"))) {
map.put("YXBZ", "");
} else {
map.put("YXBZ", map0.get("yxbz"));
}
if (Tool.isEmptyStr(map0.get("yxbzrm"))) {
map.put("YXBZRM", "");
} else {
map.put("YXBZRM", map0.get("yxbzrm"));
}
\t\t\t
if (Tool.isEmptyStr(map0.get("ysgjjd"))) {
map.put("YSGJJD", "");
} else {
map.put("YSGJJD", map0.get("ysgjjd"));
}
if (Tool.isEmptyStr(map0.get("sqyssj"))) {
map.put("SQYSSJ", "");
} else {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
String string = map0.get("sqyssj");
Date parse = null;
try {
parse = simpleDateFormat.parse(string);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String format = simpleDateFormat.format(parse);
StringBuilder myName = new StringBuilder(format);
myName.setCharAt(4, 'year');
myName.setCharAt(7, 'month');
myName.append("日");

System.out.println(myName);
//Time becomes year, month and day format
map.put("SQYSSJ", myName.toString());
}
if (Tool.isEmptyStr(map0.get("czwt"))) {
map.put("CZWT", "");
} else {
map.put("CZWT", map0.get("czwt"));
}
map.put("SJDW", "Design Unit");
map.put("JLDW", "Supervision");
map.put("BD", "121");
map.put("SDJG", "Good structure");
map.put("CD", "length 1");
map.put("JCJ", "Wellhead 1");
\t\t\t
String hh="<img width="249" height="273" src="http://192.168.200.86:18080/XSGL/2023-07-27/20230802155008.jpg",<img width="249" height="273" src="http://192.168.200.86:18080/XSGL/2023-07-27/20230802154952.jpg"";
map.put("TFT", "");
// map.put("PSZP", hh);
// map.put("YSGJJD", "Sassa");
\t\t\t
\t\t\t
} else {

map.put("SJDW", "");
map.put("JLDW", "");
map.put("BD", "");
map.put("SDJG", "");
map.put("CD", "");
map.put("JCJ", "");
map.put("TFT", "");
}
try {
WordUtils.exportWorde(request, response, map, "scbzjystd.ftl",
ysdName);
} catch (IOException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
}
}
}

The format height and width of the image are set in advance in the code, and then we can replace it with a placeholder in the template.

Set download format

 public static void exportWorde(HttpServletRequest request,
HttpServletResponse response, Map<String, Object> map,
String templateName, String fileName) throws IOException {
String pathString = request.getSession().getServletContext().getRealPath("/WEB-INF/templete/");
    logger.info("The obtained template path is: templatePath------->" + pathString);
    configuration.setDirectoryForTemplateLoading(new File(pathString));
    \t
    Template freemarkerTemplate = configuration.getTemplate(templateName);
        File file = null;
        InputStream fin = null;
        ServletOutputStream out = null;
        try {
            //Call the createDoc method of the tool class to generate a Word document
            file = createDoce(map,freemarkerTemplate);
            fin = new FileInputStream(file);
 
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/msword");
            //Set the browser to process the file name as a download
            fileName = fileName + DateUtil.currentDateToString() + ".doc";
            response.setHeader("Content-Disposition", "attachment;filename="
                    .concat(String.valueOf(URLEncoder.encode(fileName, "UTF-8"))));
 
            out = response.getOutputStream();
            byte[] buffer = new byte[512]; // buffer
            int bytesToRead = -1;
            // Output the content of the read Word file to the browser through a loop
            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(); // Delete temporary files
        }
\t\t
}

Set encoding:

 private static File createDoce(Map<String, Object> dataMap, Template template) {
        String name = ".doc";
        File f = new File(name);
        Template t = template;
        try {
            // FileWriter cannot be used in this place because the encoding type needs to be specified, otherwise the generated Word document will not be opened because of unrecognized encoding.
            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;
    }

Export effects

If this article is helpful to you, please click three times, maybe it will be used in later work.