You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
85 lines
1.9 KiB
85 lines
1.9 KiB
1 year ago
|
package com.teaching.backend.utils;
|
||
|
|
||
|
import freemarker.template.Configuration;
|
||
|
import freemarker.template.Template;
|
||
|
import freemarker.template.TemplateException;
|
||
|
import lombok.Data;
|
||
|
|
||
|
|
||
|
import java.io.*;
|
||
|
import java.net.URLDecoder;
|
||
|
import java.util.Map;
|
||
|
import java.util.Random;
|
||
|
|
||
|
/**
|
||
|
* @Author:youhang
|
||
|
* @Date:2024-05-30-18:20
|
||
|
* @Description:
|
||
|
*/
|
||
|
@Data
|
||
|
public class WordUtil {
|
||
|
|
||
|
private Configuration configuration = null;
|
||
|
|
||
|
/*
|
||
|
* 模板文件存放的目录
|
||
|
*/
|
||
|
private String baseDir;
|
||
|
|
||
|
/*
|
||
|
* 模板文件名称
|
||
|
*/
|
||
|
private String templateFile;
|
||
|
|
||
|
/*
|
||
|
* word生成的输出目录
|
||
|
*/
|
||
|
private String outputDir;
|
||
|
|
||
|
public WordUtil(){
|
||
|
configuration = new Configuration();
|
||
|
configuration.setDefaultEncoding("UTF-8");
|
||
|
}
|
||
|
|
||
|
/*
|
||
|
* <p>转换成word<br>
|
||
|
*/
|
||
|
public String createWord(Map<String,Object> dataMap){
|
||
|
|
||
|
configuration.setClassForTemplateLoading(this.getClass(), "");//模板文件所在路径
|
||
|
|
||
|
Template t = null;
|
||
|
|
||
|
try {
|
||
|
//得到模板文件
|
||
|
configuration.setDirectoryForTemplateLoading(new File(baseDir));
|
||
|
t = configuration.getTemplate(templateFile);
|
||
|
} catch (IOException e) {
|
||
|
e.printStackTrace();
|
||
|
}
|
||
|
|
||
|
//随机生成
|
||
|
Random random=new Random();
|
||
|
|
||
|
File outFile = new File(outputDir+ random.nextInt(200) + ".docx"); //导出文件
|
||
|
|
||
|
Writer out = null;
|
||
|
try {
|
||
|
out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile)));
|
||
|
} catch (FileNotFoundException e1) {
|
||
|
e1.printStackTrace();
|
||
|
}
|
||
|
try {
|
||
|
t.process(dataMap, out); //将填充数据填入模板文件并输出到目标文件
|
||
|
return outFile.getPath();
|
||
|
} catch (TemplateException e) {
|
||
|
e.printStackTrace();
|
||
|
} catch (IOException e) {
|
||
|
e.printStackTrace();
|
||
|
}
|
||
|
return "文档生成失败";
|
||
|
}
|
||
|
|
||
|
|
||
|
}
|