gradle依赖:
implementation 'org.freemarker:freemarker:2.3.31'
implementation fileTree('../lib') { include '*.jar' }
模版地址:
必要jar包:
spire.doc.free-5.2.0.jar
我这里就直接贴代码了
导包:
import cn.hutool.core.collection.CollectionUtil;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.td.base.commons.ApiException;
import com.td.base.mappers.TStationPimMapper;
import com.td.base.models.TSerialized;
import com.td.base.models.TSerializedItems;
import com.td.base.models.TStationPim;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
public void downStatement(String serialNo, Integer isPdf, HttpServletResponse response) {
Map<String, Object> map = new HashMap<String, Object>();
TStationPim one =
lambdaQuery()
.eq(TStationPim::getSerialNo, serialNo)
.orderByDesc(TStationPim::getOutTime)
.last("limit 1")
.one();
if (Objects.nonNull(one)) {
List<TSerialized> list =
tSerializedService
.lambdaQuery()
.eq(TSerialized::getSerialNo, one.getSerialNo())
.eq(TSerialized::getStationNo, one.getStationNo())
.list();
if (CollectionUtil.isNotEmpty(list)) {
AtomicReference<String> result = new AtomicReference<>("Pass");
list.forEach(
x -> {
if ("Fail".equals(x.getResult())) {
result.set("Fail");
}
});
List<TSerializedItems> data =
tSerializedItemsService
.lambdaQuery()
.in(
TSerializedItems::getSerializedId,
list.stream().map(TSerialized::getId).collect(Collectors.toList()))
.orderByDesc(TSerializedItems::getId)
.list();
map.put("lastTime", one.getOutTime());
map.put("serialNo", one.getSerialNo());
map.put("result", result.get());
map.put("productId", list.get(0).getProductId());
map.put("productDescription", list.get(0).getProductDescription());
if (CollectionUtil.isNotEmpty(data)) {
map.put("data", data);
}
try {
exportFile2(map, "序列号模版.ftl", "报表", response);
} catch (Exception e) {
throw new ApiException("9001", "参数错误!");
}
}
} else {
throw new ApiException("9001", "参数错误!");
}
}
/** 公共方法 */
public void exportFile(
Map<String, Object> data, String name, String fileName, HttpServletResponse response)
throws Exception {
// 业务代码
// 创建配置类
Configuration configuration = new Configuration(Configuration.getVersion());
configuration.setClassForTemplateLoading(this.getClass(), "/templates");
// 获取模板文件
Template template = configuration.getTemplate(name);
String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, data);
InputStream inputStream = IOUtils.toInputStream(content);
ServletOutputStream out = null;
try {
// 输出文件
response.setHeader("content-type", "application/octet-stream");
response.setContentType("application/octet-stream;charset=UTF-8");
response.setHeader(
"Content-Disposition",
"attachment;filename="
.concat(String.valueOf(URLEncoder.encode(fileName, "UTF-8") + ".doc")));
out = response.getOutputStream();
byte[] buffer = new byte[1024]; // 缓冲区
int bytesToRead = -1;
// 通过循环将读入的Word文件的内容输出到浏览器中
while ((bytesToRead = inputStream.read(buffer)) != -1) {
out.write(buffer, 0, bytesToRead);
}
} catch (Exception e) {
log.error("导出异常{" + e.getMessage() + "}");
throw new ApiException("9999");
} finally {
try {
if (out != null) {
out.flush();
}
if (out != null) {
out.close();
}
inputStream.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
/** 公共方法 */
public void exportFile2(
Map<String, Object> data, String name, String fileName, HttpServletResponse response)
throws TemplateException, IOException {
// 业务代码
// 创建配置类
Configuration configuration = new Configuration(Configuration.getVersion());
configuration.setClassForTemplateLoading(this.getClass(), "/templates");
// 获取模板文件
Template template = configuration.getTemplate(name);
String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, data);
String filePath = "/data" + fileName + ".pdf";
try (InputStream inputStream = IOUtils.toInputStream(content)) {
Document document = new Document();
document.loadFromStream(inputStream, FileFormat.Auto);
document.saveToFile(filePath, FileFormat.PDF);
}
File file = new File(filePath);
FileInputStream inputStream = new FileInputStream(file);
// InputStream inputStream = IOUtils.toInputStream(content);
ServletOutputStream out = null;
try {
// 输出文件
response.setHeader("content-type", "application/octet-stream");
response.setContentType("application/octet-stream;charset=UTF-8");
response.setHeader(
"Content-Disposition",
"attachment;filename="
.concat(String.valueOf(URLEncoder.encode(fileName, "UTF-8") + ".pdf")));
out = response.getOutputStream();
byte[] buffer = new byte[1024]; // 缓冲区
int bytesToRead = -1;
// 通过循环将读入的Word文件的内容输出到浏览器中
while ((bytesToRead = inputStream.read(buffer)) != -1) {
out.write(buffer, 0, bytesToRead);
}
} catch (Exception e) {
log.error("导出异常{" + e.getMessage() + "}");
throw new ApiException("9999");
} finally {
try {
if (out != null) {
out.flush();
}
if (out != null) {
out.close();
}
inputStream.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}