`
康敏栋
  • 浏览: 169181 次
  • 性别: Icon_minigender_1
社区版块
存档分类
最新评论

java导出含图片的word

阅读更多
导出方式将word中的模板另存为xml形式,再将xml代码拷入jsp页面,其中项目中的图片上传保存在tomcat中

方法:获取图片的路径从而得到图片,再将图片装换成base64码,再在刚才的jsp页面${images}即可

1.在word模板中先插入一张图片,再将生成的xml代码放到ExportWord.jsp中,将刚才插入的图片的base64码(就是很多那个十六进制的东西)去掉,再在该jsp的顶部加上
<%@page contentType="application/msword; charset=UTF-8"%><%@ taglib
	prefix="s" uri="/struts-tags"%><%response.addHeader("Content-Disposition",
					"attachment;filename="+request.getAttribute("strExpFileName")+".doc");%><?xml version="1.0" encoding="UTF-8" standalone="yes"?>

注:此处代码最好原封不动的,不要给它换行或者调换代码位置,因为如果此处甚至一换行都有可能到时候导出时word提示有错误,我之前特意试过,至于原因自己也不知道

2.后台代码
将将图片转成base64码的方法
  /**
	 * 将图片转成base64码
	 * @return
	 */
	public static String getImageBinary(String imagepath) {
		File f = new File(imagepath);
		BufferedImage bi;
		try {
			bi = ImageIO.read(f);
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			ImageIO.write(bi, "jpg", baos);
			byte[] bytes = baos.toByteArray();

			return encoder.encodeBuffer(bytes).trim();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

调用该方法
//通过一系列方法通过tomcat获取你想要图片的路径,例如下面是方法之一
ServletActionContext.getServletContext().getRealPath("此处写上图片存储的路径")
//现在如果已经取到了你想要的图片的路径saveFilePath。例如
saveFilePath="C:\Program Files\.....\abcd.png";
//将“\”换成“\\”,调用getImageBinary方法时得是“\\”
saveFilePath=saveFilePath.replace("\\", "\\\\");
StringBuilder str=new StringBuilder();
//取得图片的base64码
str.append(getImageBinary(saveFilePath));
images=str.toString();//images就是图片的base64码
//此处的strExpFileName就是ExportWord.jsp中上面的变量名
strExpFileName=new String("导出图片".getBytes("GB2312"), "8859_1");


3.在ExportWord.jsp中刚才去掉base64码的位置加上
${images}
分享到:
评论
1 楼 18335864773 2019-04-02  
推荐用 pageoffice 导出 word ,不需要另存 xml 文件,也不需要把图片转成 base64位。代码调用非常简单。

相关推荐

Global site tag (gtag.js) - Google Analytics