我这是用easypoi导出docx文档
docx 模板 字段用 {{ }} 包含
easypoi 地址 ( http://doc.wupaas.com/docs/easypoi/easypoi-1c3a7tlsc85jn )
例:
/**
maven依赖
**/
<!-- 导出docx -->
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-spring-boot-starter</artifactId>
<version>4.0.0</version>
</dependency>
/**
业务层
**/
@SneakyThrows
@Override
public void downloadWord(PerformanceSecurityVO entity, HttpServletResponse response) {
String fileName = "测试.docx";
//实体转map
Map result = JSON.parseObject(JSON.toJSONString(entity), Map.class);
// Map<String, Object> result = EasyPoiUtil.entityToMap(entity);
EasyPoiUtil.downloadWord(fileName, result, response);
}
import cn.afterturn.easypoi.word.WordExportUtil;
import com.ylxx.cloud.exception.ext.ServiceException;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.util.ResourceUtils;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
public class EasyPoiUtil {
public static void downloadWord(String fileName, Map<String, Object> params, HttpServletResponse response) {
String path = getPath(fileName);//我这放 resources包下
try {
//获取模板文档
File rootFile = new File(ResourceUtils.getURL("classpath:").getPath());
File file= new File(rootFile, path);
XWPFDocument word = WordExportUtil.exportWord07(file.getPath(), params);
response.setCharacterEncoding("utf-8");
response.setContentType("multipart/form-data");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
OutputStream out = response.getOutputStream();
word.write(out);
out.flush();
out.close();
} catch (Exception e) {
throw new ServiceException("导出失败,请联系网站管理员!", e);
}
}
public static String getPath(String filename) {
filename = "/word/" + filename;
return filename;
}
/**
实体类转Map
*/
public static Map<String, Object> entityToMap(Object object) {
Map<String, Object> map = new HashMap<>();
for (Field field : object.getClass().getDeclaredFields()) {
try {
boolean flag = field.isAccessible();
field.setAccessible(true);
Object o = field.get(object);
map.put(field.getName(), o);
field.setAccessible(flag);
} catch (Exception e) {
e.printStackTrace();
}
}
return map;
}
}