Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

Importing dependencies into POM files

<! Deepoove </groupId> <artifactId> Poi-tl </artifactId> <version>1.7.3</version> </dependency> <! Poi </groupId> <artifactId> Poi-ooxml </artifactId> <version>4.1.0</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>4.1.2</version> </dependency>Copy the code

Make a template file docx for exporting Word, as shown in the picture

Java exports word code

import com.deepoove.poi.XWPFTemplate; import com.deepoove.poi.config.Configure; import com.deepoove.poi.policy.HackLoopTableRenderPolicy; import com.google.common.collect.Lists; import java.io.FileOutputStream; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @Description: * @Author: Tarzan Liu * @Date: 2020/4/2 14:54 */ public class test { public static void test(){ HackLoopTableRenderPolicy policy = new HackLoopTableRenderPolicy(); Configure config = Configure.newBuilder().bind("list", policy).build(); List<Map<String, Object>> list= Lists.newArrayList(); for (int i = 0; i < 5; i++) { Map<String, Object> data = new HashMap<>(); Data. put("year","201"+ I); data.put("num",33+i); list.add(data); } Map<String, Object> data = new HashMap<>(); Data. put("list",list); XWPFTemplate template = XWPFTemplate.compile("E:\\test\\ccc.docx",config).render(data); Try {FileOutputStream out = new FileOutputStream("E:\ test\ test.docx"); // The name of the file to export template.write(out); out.flush(); out.close(); template.close(); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { test.test(); }}Copy the code

Idea Running output diagram

The exported file is shown in the figure