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.
71 lines
1.8 KiB
71 lines
1.8 KiB
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.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; |
|
private String outputDir; |
|
private InputStream templateInputStream; // 模板文件输入流 |
|
|
|
public WordUtil() { |
|
configuration = new Configuration(); |
|
configuration.setDefaultEncoding("UTF-8"); |
|
} |
|
|
|
public void setTemplateInputStream(InputStream templateStream) { |
|
this.templateInputStream = templateStream; |
|
} |
|
|
|
public String createWord(Map<String,Object> dataMap) { |
|
configuration.setClassForTemplateLoading(this.getClass(), ""); |
|
|
|
Template t = null; |
|
try { |
|
t = new Template(templateFile, new InputStreamReader(templateInputStream, "UTF-8"), configuration); |
|
} 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))); |
|
|
|
t.process(dataMap, out); |
|
|
|
return outFile.getPath(); |
|
|
|
} catch (TemplateException | IOException e) { |
|
e.printStackTrace(); |
|
} finally { |
|
if (out != null) { |
|
try { |
|
out.close(); |
|
} catch (IOException e) { |
|
e.printStackTrace(); |
|
} |
|
} |
|
} |
|
|
|
return "文档生成失败"; |
|
} |
|
} |