用途:生成電子履歷或者固定格式文檔
依賴:
<dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.30</version> </dependency>
代碼:
1 import freemarker.template.Configuration; 2 import freemarker.template.Template; 3 import org.springframework.core.io.ByteArrayResource; 4 import org.springframework.core.io.InputStreamSource; 5 6 import java.io.*; 7 import java.nio.charset.StandardCharsets; 8 import java.util.Map; 9 10 /** 11 * @program: world 12 * @description: doc工具類 13 * @author: XinHai.Ma 14 * @create: 2021-09-09 15:54 15 */ 16 public class DocUtils { 17 18 public static void saveWord(String filePath, Map<String,Object> dataMap) throws IOException { 19 Configuration configuration = new Configuration(); 20 configuration.setDefaultEncoding("utf-8"); 21 configuration.setClassForTemplateLoading(DocUtils.class, "/"); 22 Template template = configuration.getTemplate("templates/template.xml"); 23 InputStreamSource streamSource = createWord(template, dataMap); 24 InputStream inputStream = streamSource.getInputStream(); 25 FileOutputStream outputStream = new FileOutputStream(filePath); 26 byte[] bytes = new byte[1024]; 27 while ((inputStream.read(bytes)) != -1) { 28 outputStream.write(bytes);// 寫入數據 29 } 30 inputStream.close(); 31 outputStream.close(); 32 } 33 34 public static InputStreamSource createWord(Template template, Map<String, Object> dataMap) { 35 StringWriter out = null; 36 Writer writer = null; 37 try { 38 out = new StringWriter(); 39 writer = new BufferedWriter(out, 1024); 40 template.process(dataMap, writer); 41 return new ByteArrayResource(out.toString().getBytes(StandardCharsets.UTF_8)); 42 } catch (Exception e) { 43 e.printStackTrace(); 44 } finally { 45 try { 46 writer.close(); 47 out.close(); 48 } catch (IOException e) { 49 e.printStackTrace(); 50 } 51 } 52 return null; 53 } 54 55 }
調用代碼:
1 import com.maxinhai.world.utils.DocUtils; 2 import org.junit.Test; 3 import org.junit.runner.RunWith; 4 import org.springframework.boot.test.context.SpringBootTest; 5 import org.springframework.test.context.junit4.SpringRunner; 6 7 import java.io.IOException; 8 import java.util.HashMap; 9 import java.util.Map; 10 11 /** 12 * @program: world 13 * @description: doc測試用例 14 * @author: XinHai.Ma 15 * @create: 2021-09-09 16:16 16 */ 17 @RunWith(SpringRunner.class) 18 @SpringBootTest 19 public class DocTests { 20 21 @Test 22 public void test() { 23 try { 24 Map<String, Object> dataMap = new HashMap<>(); 25 dataMap.put("title", "獻祭之主"); 26 dataMap.put("author", "王信"); 27 dataMap.put("createDate", "2021年9月9日"); 28 dataMap.put("title_item1", "第14章 :我父母為了保護北馬城所犧牲!"); 29 dataMap.put("content", "我父母為了保護北馬市,死在了魔獸攻城中!"); 30 DocUtils.saveWord("C:\\Users\\86186\\Documents\\獻祭之主.docx", dataMap); 31 } catch (IOException e) { 32 e.printStackTrace(); 33 } 34 } 35 36 }
模板制作:
1. 新建一個word文檔,填入固定內容;
2. 在要用程序寫入數據的地方,插入-文檔部件-域-自動圖文集列(微軟Word叫AUTOTEXTLIST),標簽名和程序標簽要對應;
3. 文檔保存為Word XML格式;
4. 放入程序要去讀取模板的路徑;
生成文檔效果: