大致的思路是先用office2003或者2007编辑好word的样式,然后另存为xml,将xml翻译为FreeMarker模板,最后用java来解析FreeMarker模板并输出Doc。经测试这样方式生成的word文档完全符合office标准,样式、内容控制非常便利,打印也不会变形,生成的文档和office中编辑文档完全一样。

用xml做导出方案。

先创建一个word文档,按照需求在word中填好一个模板,然后把对应的数据换成变量${},然后将文档保存为xml文档格式,使用文档编辑器打开这个xml格式的文档,去掉多余的xml符号,使用Freemarker读取这个文档然后替换掉变量,输出word文档即可

需要freemarker jar包

/**

Project Name:exam-services

File Name:DownloadService.java

Package Name:com.wt.service.download

Date:2016年9月28日下午4:44:37

Copyright (c) 2016, chenzhou1025@126.com All Rights Reserved.

*/

package com.wt.service.download;

import java.io.BufferedInputStream;

import java.io.BufferedOutputStream;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import java.net.URLEncoder;

import java.text.SimpleDateFormat;

import java.util.Date;

import javax.servlet.http.HttpServletResponse;

import net.paoding.rose.web.Invocation;

import org.apache.log4j.Logger;

import org.springframework.stereotype.Service;

/**

ClassName:DownloadService

Function: 文件下载.

Reason: ADD REASON.

Date: 2016年9月28日 下午4:44:37

@author wpengfei

@version

@since JDK 1.6

@see

*/

@Service

public class DownloadService {

private Logger logger = Logger.getLogger(this.getClass());

/**

* downLoad:(文件下载).

*

* @author wpengfei

* @param inv

* @param fileName

* @param path

* @throws IOException

* @since JDK 1.6

*/

public void downLoad(Invocation inv, String fileName, String path) throws IOException {

File file = new File(path);// 构造要下载的文件

if (file.exists()) {

InputStream ins = null;

BufferedInputStream bins = null;

OutputStream outs = null;

BufferedOutputStream bouts = null;

try {

ins = new FileInputStream(path);// 构造一个读取文件的IO流对象

bins = new BufferedInputStream(ins);// 放到缓冲流里面

outs = inv.getResponse().getOutputStream();// 获取文件输出IO流

bouts = new BufferedOutputStream(outs);

String path1 = inv.getRequest().getSession().

getServletContext().getRealPath("/WEB-INF/downloads");

logger.info(path1);

inv.getResponse().setContentType("application/x-download");// 设置response内容的类型

inv.getResponse().setHeader("Content-disposition",

"attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));// 设置头部信息

// inv.getResponse().setContentLength((int)file.length());

int bytesRead = 0;

byte[] buffer = new byte[8192];

// 开始向网络传输文件流

while ((bytesRead = bins.read(buffer, 0, 8192)) != -1) {

bouts.write(buffer, 0, bytesRead);

}

bouts.flush();// 这里一定要调用flush()方法

} catch (Exception e) {

e.printStackTrace();

} finally {

if (bouts != null) {

bouts.close();

}

if (outs != null) {

outs.close();

}

if (bins != null) {

bins.close();

}

if (ins != null) {

ins.close();

}

}

} else {

logger.info("导出的文件不存在");

}

}

}

package com.wt.common.util;

import java.io.BufferedWriter;

import java.io.File;

import java.io.FileOutputStream;

import java.io.OutputStreamWriter;

import java.io.Writer;

import java.util.Map;

import freemarker.template.Configuration;

import freemarker.template.Template;

/**

@Desc:word操作工具类

@Author:

@Date:2014-1-22下午05:03:19

*/

public class WordUtil {

@SuppressWarnings("rawtypes")

public static String createWord2(Map dataMap, String templateName, String filePath, String fileName) {

try {

// 创建配置实例

Configuration configuration = new Configuration();

// 设置编码

configuration.setDefaultEncoding("UTF-8");

// ftl模板文件统一放至 com.lun.template 包下面

configuration.setClassForTemplateLoading(WordUtil.class, "\\com\\wt\\common\\util\\");

// 获取模板

Template template = configuration.getTemplate(templateName);

// 输出文件

File outFile = new File(filePath + File.separator + fileName);

// 如果输出目标文件夹不存在,则创建

if (!outFile.getParentFile().exists()) {

outFile.getParentFile().mkdirs();

}

// 将模板和数据模型合并生成文件

Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "UTF-8"));

// 生成文件

template.process(dataMap, out);

// 关闭流

out.flush();

out.close();

return filePath + File.separator + fileName;

} catch (Exception e) {

e.printStackTrace();

}

return null;

}

}

package com.wt.controllers.test1;

import java.io.IOException;

import java.text.SimpleDateFormat;

import java.util.ArrayList;

import java.util.Date;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

import java.util.Random;

import net.paoding.rose.web.Invocation;

import net.paoding.rose.web.annotation.Path;

import net.paoding.rose.web.annotation.rest.Get;

import org.apache.commons.lang.StringUtils;

import org.springframework.beans.factory.annotation.Autowired;

import com.wt.common.util.CommonsUtil;

import com.wt.common.util.Constants;

import com.wt.common.util.ResponseObject;

import com.wt.common.util.WordUtil;

import com.wt.service.download.DownloadService;

/**

@Desc:生成word

@Author:

@Date:2014-1-22下午04:52:03

*/

@Path("/word")

public class WordController {

@Autowired

private DownloadService downloadService;

private String filePath; //文件路径

// private String fileName; //文件名称

private String fileOnlyName; //文件唯一名称

/**

* createWord2:(这里用一句话描述这个方法的作用).

* localhost:8080/test1/word/createWord2

*

* @author wpengfei

* @param inv

* @return

* @throws IOException

* @since JDK 1.6

*/

@Get("/createWord2")

public String createWord2(Invocation inv) throws IOException {

/** 用于组装word页面需要的数据 */

Map dataMap = new HashMap();

SimpleDateFormat sdf=new SimpleDateFormat("yyyy年MM月dd日");

dataMap.put("startTime", sdf.format(new Date()));

dataMap.put("endTime", sdf.format(new Date()));

dataMap.put("count", 1);

dataMap.put("username", "Tom");

dataMap.put("courseName", "物理");

dataMap.put("className", "1班");

dataMap.put("materialName", "体育学");

dataMap.put("materialVer", 1.0);

dataMap.put("teachAim", "诺克尔12421价是否可骄傲了空间阿凡达捡垃圾覅文件附件安防奇偶万佛诺克尔12421价是否可骄傲了空间阿凡达捡垃圾覅文件附件安防奇偶万佛诺克尔12421价是否可骄傲了空间阿凡达捡垃圾覅文件附件安防奇偶万佛诺克尔12421价是否可骄傲了空间阿凡达捡垃圾覅文件附件安防奇偶万佛诺克尔12421价是否可骄傲了空间阿凡达捡垃圾覅文件附件安防奇偶万佛");

//文件导出的目标路径

filePath=Constants.UPLOAD_BASE_FOLD;

StringBuffer sb=new StringBuffer();

sb.append(sdf.format(new Date()));

sb.append("_");

Random r=new Random();

sb.append(r.nextInt(100));

//文件唯一名称

fileOnlyName = "testDoc11_"+sb+".doc";

/** 生成word */

String result = WordUtil.createWord2(dataMap, "testDoc11.ftl", filePath, fileOnlyName);

if(StringUtils.isNotBlank(result)){

downloadService.downLoad(inv, fileOnlyName, result);

}

return "@";

}

}

java xml转换word_java如何将xml类型的word文档转换为word类型的文档相关推荐

  1. setTimeStamp()与setDate()区别 如何将java中Date存入mysql中的datetime中,字符串怎么转换为日期类型

    数据库 1.java.sql.Date 与 java.util.Date java.sql.Date是从java.util.Date中继承而来 假设 dates1(java.sql.Date)要赋值给 ...

  2. java pdf 转换 word_Java 将PDF 转为Word、图片、SVG、XPS、Html、PDF/A

    本文将介绍通过Java编程来实现PDF文档转换的方法.包括: 1. PDF转为Word 2. PDF转为图片 3. PDF转为Html 4. PDF转为SVG 4.1将PDF每一页转为单个的SVG 4 ...

  3. java bean与xml转换_Java Bean与xml互相转换的方法分析

    本文实例讲述了Java Bean与xml互相转换的方法.分享给大家供大家参考,具体如下: XML和Java Bean互相转换是一个很有用的功能,因为两者有着前后合作的关系,但解析的过程比较痛苦.下面介 ...

  4. java xsl转换pdf_Java 生成PDF文档-阿里云开发者社区

    最近项目需要实现PDF下载的功能,由于没有这方面的经验,从网上花了很长时间才找到相关的资料.整理之后,发现有如下几个框架可以实现这个功能. 1. 开源框架支持 iText,生成PDF文档,还支持将XM ...

  5. java自动转换与强制转换

    前言 本文转自 http://blog.csdn.net/Mailbomb/article/details/2449261 文章中添加了一些在阅读时的感悟(阅读笔记) 正文 数据类型转换 Java语言 ...

  6. mysql中将长整型转换为时间类型或将时间类型转换为长整型

    长整型转换为时间类型的关键字:FROM_UNIXTIME(长整型,format): 时间类型转换为长整型的关键字:UNIX_TIMESTAMP(时间类型): 长整型转换为时间类型例子:select F ...

  7. Springboot-Vue-MybatisPlus 返回给前端的 Long类型数据失去精度怎么办 之 Long类型作为实体类的一个属性

    Springboot-Vue-MybatisPlus 返回给前端的 Long类型数据失去精度怎么办? 在将自己的Mybatis的系统转换为Mybatis-Plus的时候,遇到了许多问题. 今天的问题是 ...

  8. java转换CSV文件生成xml格式数据

    注册CSDN快六个月了,之前一直是看园子里的文章,或者碰到问题时,进来查点资料,今天终于决定写一篇自己在园子里的blog. 好吧,鉴于水平太菜,就只记录过程,其中原理啥的并不是很明晰,所以此blog只 ...

  9. java xml amp_Javaamp;Xml教程(十一)JAXB实现XML与Java对象转换

    JAXB是Java Architecture for XML Binding的缩写,用于在Java类与XML之间建立映射,可以帮助开发人员非常方便的將XML和Java对象进行相互转换. 本文以一个简单 ...

最新文章

  1. Mac OS X 下连接CMCC无法弹出登陆页面问题
  2. CSDN Blog V3.0.0.2升级公告
  3. 去掉桌面快捷方式小箭头的方法
  4. 怎么安装Scrapy框架以及安装时出现的一系列错误(win7 64位 python3 pycharm)
  5. mysql php释放内存_php mysqli_free_result()函数释放结果集
  6. SpringBoot (14)---日志配置(logback)
  7. 1342.将数字变成0的操作次数
  8. flex socket java_使用Java编写Socket服务器,并且与Flex通信(二)
  9. 我的世界Java版最诡异的种子_我的世界:MC出现诡异的种子,地域不停地重复
  10. Brackets - (HTML/CSS/JavaScript 前端 WEB IDE) 使用技巧
  11. VSCode必备安装插件
  12. 互联网+创新创业大赛反思总结
  13. ESLint和Prettier的配置
  14. leetcode174.地下城游戏
  15. 使用python批量解压7z格式压缩包
  16. RuntimeError: xxx.pth is a zip archive (did you mean to use torch.jit.load()?)
  17. 银行理财子与券商合作探讨(一):银行理财子带给资本市场的机遇与挑战
  18. 浅谈敏捷思想-08.从产品愿景到用户故事地图
  19. 中国2019最有价值的科幻类影视游戏IP 网络科幻小说《公元2119年》、
  20. 【JavaWeb学习】Vue核心

热门文章

  1. 微信支付v2开发(9) 标记客户投诉处理状态
  2. k线图入门与技巧:浪波理论与K线形态
  3. iOS打印当前控制器名称、事件名称
  4. 汉字编码标准与识别(转)
  5. maven仓库报错 MavenResportException: Error while generating Javadoc:
  6. Linux密码生成工具crunch使用攻略
  7. d58站群inc.php,D58站群2018年版本SEO特殊字符静态文件生成根目录源码分享
  8. JAVA对文件进行压缩和解压
  9. 完美解决WebSocket 服务器 The WebSocket session [0] has been closed and no method...异常信息
  10. 弹性地基梁板法计算原理_地下连续墙静力计算和分析.pdf