java使⽤freemarker完美导出word⽂档(带图)
poi
java2word
freemarker
最后选⽤freemarker,为什么呢?业务需要。
⽣成doc格式,⽐较简单,这⾥就不列举了,⽹上有⼤量的例⼦
⽣成思路⼤概就是保存⼀个doc⽂件,改后缀位xml,占位符去渲染。其中图⽚转换成base64格式。
这⾥主要讲docx格式。测试环境office 2013 2016
特殊符号需要转义,否则报错
docx格式本质上是个zip压缩包。
1. 新建docx⽂件,插⼊⾃⼰需要的格式,如图
2. 修改后缀为zip
[Content_Types].xml
如果需要插图,需要修改此⽂件,这⾥以jpg图⽚为例,
插⼊图⽚word转为jpeg,建议图⽚修改jpg为jepg
如果插⼊其他格式在此⽂件夹添加对应的说明
3.打开word⽂件夹,主要改动也是在这⾥
注意: <pic:cNvPr id=“1” name=“图⽚ 1”/> 中的id最好使⽤数字,前⾯使⽤的字符串出现打开⽂件弹错误的情况=====================================================================
=====================================================================⼲货来了
⽬录结构
springboot maven引⼊freemarker
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
2022年庆祝国庆73周年</dependency>
freemarker相关配置
这⾥就不啰嗦了
spring:
freemarker:
charset: UTF-8
suffix:.html
template-loader-path:/templates
content-type: text/html; charset=utf-8
java ⼯具类
import java.io.*;
import java.util.Date;
import date.DateUtil;
祝所有劳动者节日快乐import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
ParseException;
plate.Configuration;
plate.MalformedTemplateNameException;
plate.Template;
plate.TemplateException;
plate.TemplateExceptionHandler;
plate.TemplateNotFoundException;
slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
/**
* @Description: word⼯具类
* @Auther: simp
* @Date: 2020/11/27 11:18
* @Version: 1.0
*/
@Slf4j
@Component
public class WordUtils {
private static final String path ="/project/upload/doc/";
public static Configuration getConfiguration(){
Configuration config =new Configuration(Configuration.VERSION_2_3_28);
config.setDefaultEncoding("utf-8");
config.setClassForTemplateLoading(WordUtils.class,"/templates");
config.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);
return config;
}
/**
dnf炼金师快速升级
* FreeMarker⽣成Word
* @param dataMap 数据
* @param templateName ⽬标名
*/
public static ByteArrayInputStream createXml(JSONObject dataMap, String templateName){
Template template = null;
ByteArrayInputStream in = null;
dsWith(".html")){
templateName = templateName.substring(0, templateName.indexOf(".html"));
}
try{
template =getConfiguration().getTemplate(templateName +".html");
}catch(TemplateNotFoundException e){
e.printStackTrace();
}catch(MalformedTemplateNameException e){
e.printStackTrace();
}catch(ParseException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
StringWriter out =new StringWriter();
try{
template.process(dataMap, out);
in =new String().getBytes("utf-8"));//这⾥⼀定要设置utf-8编码否则导出的word中中⽂会是乱码}catch(TemplateException e){
e.printStackTrace();
}catch(IOException e){临沂有什么好玩的地方旅游景点
e.printStackTrace();
}
作文500字try{
out.close();
}catch(IOException e){
e.printStackTrace();
}
return in;
}
public static String exportWord(String report){
JSONObject jsonObject = JSONObject.parseObject(report);
Date date =new Date(Long.String("time")));
String docName =new StringBuffer()
.append(DateUtil.format(date,"yyyyMMddHHmmss"))
.append("_")
.String("taskName"))
.append(".docx").toString();
String saveFilePath = path + docName;
String time = DateUtil.format(date,"yyyy/MM/dd HH:mm:ss");
jsonObject.put("time", time);
word打开是乱码JSONArray stepInfos = JSONArray("stepInfos");
JSONArray images =new JSONArray();
int count =10;
for(Object item : stepInfos){
JSONObject step =(JSONObject) item;
ainsKey("images")){
JSONArray list = JSONArray("images");
for(Object it : list){
JSONObject image =(JSONObject) it;
ainsKey("path")){
ainsKey("path")){
image.put("id", count);
image.put("embed","rId"+ count);
image.put("name","图⽚ "+ count);
String path = String("path");
String ext = path.substring(path.lastIndexOf("."));
ext =".jpg".equals(ext)?".jpeg": ext;
JSONObject imageJson =new JSONObject();
imageJson.put("embed", String("embed"));
imageJson.put("id", String("id"));
imageJson.put("ext", ext);
imageJson.put("name","image"+ count + ext);
try{
FileInputStream fileIn =new String("path"));
imageJson.put("code", fileIn);
}catch(Exception e){
}
images.add(imageJson);
count++;
}
}
}
}
JSONObject imageObject =new JSONObject();
imageObject.put("images", images);
ZipOutputStream zipout = null;
OutputStream outputStream = null;
try{
ByteArrayInputStream documentInput =createXml(jsonObject,"report.html");
ByteArrayInputStream documentXmlRelsInput =createXml(imageObject,"report_images.html");
File docxFile =new File(ClassLoader().getResource("templates/report.zip").getPath());
if(!ists()){
}
ZipFile zipFile =new ZipFile(docxFile);
Enumeration<?extends ZipEntry> zipEntrys = ies();
File outFile =new File(saveFilePath);
if(!ParentFile().exists()){
}
outputStream =new FileOutputStream(outFile);
zipout =new ZipOutputStream(outputStream);
/
/ 覆盖⽂档
int len =-1;
byte[] buffer =new byte[1024];
while(zipEntrys.hasMoreElements()){
ZipEntry next = Element();
InputStream is = InputStream(next);
String().indexOf("media")<0){
zipout.putNextEntry(new Name()));
Name().indexOf("ls")>0){
if(documentXmlRelsInput != null){
while((len = ad(buffer))!=-1){
zipout.write(buffer,0, len);
}
documentXmlRelsInput.close();
}
}else if("l".Name())){
if(documentInput != null){
while((len = ad(buffer))!=-1){
zipout.write(buffer,0, len);
}
documentInput.close();
}
}else{
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论