导出word,引用的是easypoi的jar
第一步:导入jar
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-base</artifactId>
<version>3.0.3</version>
</dependency>
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-web</artifactId>
<version>3.0.3</version>
</dependency>
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-annotation</artifactId>
<version>3.0.3</version>
</dependency>
第二步:
编辑word文档 ,easypoi支持word版本为2007的
xxx.docx
记得使用英文输入法 :{}

将建好的模板放到项目里名为word文件夹下
第三步:开始编辑代码
传入的是defExpert对象,对象中的属性赋值给word文档上
首先模板中用到了图片,从服务器下载图片到本地,设置在word中显示的高度和宽度使用WordImageEntity对象。

图中的第一步:把图片下载到本地调用outImage方法
![]()
public void outImage(String path,String localPath,String name) { //
HttpURLConnection conn = null;
InputStream inputStream = null;
BufferedInputStream bis = null;
FileOutputStream out = null;
try
{
File file0=new File(localPath);
if(!file0.isDirectory()&&!file0.exists()){
file0.mkdirs();
}
out = new FileOutputStream(file0+"\\"+name+".jpg");
// 建立链接
URL httpUrl=new URL(path);
conn=(HttpURLConnection) httpUrl.openConnection();
//以Post方式提交表单,默认get方式
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.setDoOutput(true);
// post方式不能使用缓存
conn.setUseCaches(false);
//连接指定的资源
conn.connect();
//获取网络输入流
inputStream=conn.getInputStream();
bis = new BufferedInputStream(inputStream);
byte b [] = new byte[1024];
int len = 0;
while((len=bis.read(b))!=-1){
out.write(b, 0, len);
}
System.out.println("下载完成...");
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
if(out!=null){
out.close();
}
if(bis!=null){
bis.close();
}
if(inputStream!=null){
inputStream.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
第二步:
map中填写属性值和word模板中的名称一致
第三步:
调用easypoi的
![]()
防止word文件名乱码
String name = java.net.URLDecoder.decode(defExpert.getName(),"utf-8"); //防止文件名乱码
以上就是使用easypoi导出word,如有什么错误或者疑问,请指教
另一种方式使用freeMarker导出word:https://blog.youkuaiyun.com/wjnjava/article/details/100288246
本文介绍了如何使用easypoi库在Java中导出Word文档,包括导入jar包、编辑Word模板,以及设置图片和属性值。通过下载图片到本地并设置高度和宽度,然后利用WordImageEntity对象和easypoi的方法完成导出。最后提到了防止文件名乱码的问题,并提供了一个使用FreeMarker导出Word的参考资料。
1万+

被折叠的 条评论
为什么被折叠?



