1.pom引入依赖:
-
com.alibaba -
easyexcel -
3.0.5 -
com.deepoove -
poi-tl -
1.10.5
2.写工具类
- package *****;
-
- import com.deepoove.poi.XWPFTemplate;
-
- import java.io.FileOutputStream;
- import java.io.IOException;
-
- public class GenerateWordUtils {
- /**
- *
- * @param path 文件模板路径
- * @param fileName 生成的文件名
- * @param param 需要替换的对象
- */
- public static String generateWord(String path,String fileName,Object param) {
- try {
- XWPFTemplate template = XWPFTemplate.compile(path).render(param);
- template.writeAndClose(new FileOutputStream(fileName));
- } catch (IOException e) {
- e.printStackTrace();
- }
- return fileName;
- }
- }
3.调用
例子:
- //相对路径在项目根目录
- String path = GenerateWordUtils.generateWord(new String(模板路径path.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8), 文件名fileName, 需替换的结果集resultMap);
- //项目路径
- String projectPath=System.getProperty("user.dir");
- //文件真实路径
- String realPath = projectPath+File.separator+path