java实现根据word模板导出数据
模板文件:
模板描述:{{?govinspectItemVOList}} 为循环遍历的数据实体
代码块:
//生成文件所在路径
String dirName = System.getProperty("user.dir") + File.separator + "file";
//模板文件存放地址
String templateFileName = dirName + File.separator + "质量安全巡查检查报告.docx";
//生成的临时文件
String fileName = "质量安全巡查检查报告" + System.currentTimeMillis() + ".docx";
WordUtils.fill(response, dirName, fileName, templateFileName, exportProjectReportVO);
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.util.FileUtils;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.config.ConfigureBuilder;
import lombok.SneakyThrows;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.*;
public class WordUtils {
/**
* @param response 输出流
* @param path 生成文件所在路径
* @param filename 文件名称
* @param templateFileName 模板名称 全路径,包含模板名称
* @param data 组装的数据
* @throws IOException
*/
public static <T> void fill(HttpServletResponse response, String path, String filename, String templateFileName,
Object data) throws IOException, IllegalAccessException {
Map<String, Object> templateData = new HashMap<>();
ConfigureBuilder builder = Configure.builder();
/**遍历数据*/
for (Field field : data.getClass().getDeclaredFields()) {
field.setAccessible(true);
Object value = field.get(data);
if (ObjectUtil.isNull(value)) {
value = "";
}
String subClassName = value.getClass().getSimpleName();
if (Arrays.asList(ApiConstants.classNames).contains(subClassName)) {
templateData.put(field.getName(), value);
} else {
if (value instanceof List<?>) {
//list 创建 tables
List<?> subList = (List<?>) value;
templateData.put(field.getName(), createTable(subList));
}
}
}
Configure config = builder.build();
// 4. 创建模板,输出模板
String tempName = templateFileName;
XWPFTemplate template = XWPFTemplate.compile(tempName, config)
.render(templateData);
File outputFile = new File(path + File.separator + filename);
template.writeToFile(path + File.separator + filename);
template.close();
if (outputFile.exists()) {
FileInputStream fis = new FileInputStream(outputFile);
ServletOutputStream sos = response.getOutputStream();
int len;
byte[] readBytes = new byte[1024];
while ((len = fis.read(readBytes)) != -1) {
sos.write(readBytes, 0, len);
}
fis.close();
// 输出 Excel
sos.flush();
sos.close();
response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, StandardCharsets.UTF_8));
response.setContentType("application/octet-stream");
//删除临时文件
outputFile.delete();
}
// 设置 header 和 contentType。写在最后的原因是,避免报错时,响应 contentType 已经被修改了
}
}