使用Aspose.Words for Java完成复杂Word与PDF的导出

使用Aspose.Words for Java 可以导出复杂WORD PDF HTML 多种数据格式
官方下载地址:http://www.aspose.com/java/word-component.aspx
我所用的版本是Aspose.Words.jdk16.jar

先看效果图

1-对数据行的导出,分别是PDF与WORD格式

2-对类似于个人简历的数据导出带图片,分别是PDF与WORD格式

[size=large]
使用该组件一共分为4个步骤
1-定义模板
2-加载模板
3-填充数据
4-设置导出格式并导出
接下来我们按照以上4个步骤进行报表的导出

首先定义模板(可以再附件中下载)这里只介绍最后一个个人简历的模板
一个普通的自定义word就可以

«TableStart:Employees»
«TableEnd:Employees»
这一对标记代表一个数据单元 Employees 是可以自定义的 填充数据源时要对应上

其他的就好理解了 比如«FirstName» 就是数据源中的属性

接下来开始我们的导出之旅吧!!!!

第一步定义一个导出的抽象类

Java代码  收藏代码
  1. package com.epkj.words;
  2. import org.springframework.stereotype.Component;
  3. import com.aspose.words.Document;
  4. @Component("ProcessWord")
  5. public abstract class ProcessWord {
  6.     public abstract Document execute(String templatePath) throws Exception;
  7. }

第二部写一个具体的实现类

Java代码  收藏代码
  1. package com.epkj.words;
  2. import java.io.FileInputStream;
  3. import java.io.IOException;
  4. import java.util.ArrayList;
  5. import java.util.HashMap;
  6. import java.util.List;
  7. import java.util.Map;
  8. import org.springframework.stereotype.Component;
  9. import com.aspose.words.Document;
  10. /**
  11.  * 带图片的导出
  12.  */
  13. @Component("EmployeesReportDemo")
  14. public class EmployeesReportDemo extends ProcessWord {
  15.     @Override
  16.     public Document execute(String templatePath) throws Exception {
  17. //1 读取模板
  18.         Document doc = new Document(templatePath + "/" + "EmployeesReportDemo.doc");
  19.         String imagePath = templatePath + "/" + "employees.jpg";
  20. //2 填充数据源
  21.         doc.getMailMerge().executeWithRegions(new MapMailMergeDataSource(getMapList(imagePath), "Employees"));
  22.         return doc;
  23.     }
  24.     private List<Map<String, Object>> getMapList(String imagePath) throws IOException {
  25.         List<Map<String, Object>> dataList = new ArrayList<Map<String,Object>>();
  26.         //读取一个二进制图片
  27.         FileInputStream fis = new FileInputStream(imagePath);
  28.         byte[] image = new byte[fis.available()];
  29.         fis.read(image);
  30.         fis.close();
  31.         for (int i = 0; i < 20; i++) {
  32.             Map<String, Object> record = new HashMap<String, Object>();
  33. //这里的key要与模板中的<<xxxxx>>对应
  34.             record.put("FirstName", "欧阳");
  35.             record.put("LastName", "夏丹");
  36.             record.put("Title", "个人简历导出Word PDF");
  37.             record.put("Address", "中国 北京市 东城区");
  38.             record.put("City", "北京");
  39.             record.put("Country", "辽宁沈阳");
  40.             //二进制数据
  41.             record.put("PhotoBLOB", image);
  42.             dataList.add(record);
  43.         }
  44.         return dataList;
  45.     }
  46. }

!!!因为Aspose.Words for Java不支持HashMap的数据格式,需要我们自己实现
好在它提供了IMailMergeDataSource接口

Java代码  收藏代码
  1. package com.epkj.words;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. import java.util.Map;
  5. import com.aspose.words.IMailMergeDataSource;
  6. /**
  7.  * 实现对HashMap的支持
  8.  */
  9. public class MapMailMergeDataSource implements IMailMergeDataSource {
  10.     private List<Map<String, Object>> dataList;
  11.     private int index;
  12.     //word模板中的«TableStart:tableName»«TableEnd:tableName»对应
  13.     private String tableName = null;
  14.     /**
  15.      * @param dataList 数据集
  16.      * @param tableName 与模板中的Name对应
  17.      */
  18.     public MapMailMergeDataSource(List<Map<String, Object>> dataList, String tableName) {
  19.         this.dataList = dataList;
  20.         this.tableName = tableName;
  21.         index = -1;
  22.     }
  23.     /**
  24.      * @param data 单个数据集
  25.      * @param tableName 与模板中的Name对应
  26.      */
  27.     public MapMailMergeDataSource(Map<String, Object> data, String tableName) {
  28.         if(this.dataList == null) {
  29.             this.dataList = new ArrayList<Map<String,Object>>();
  30.             this.dataList.add(data);
  31.         }
  32.         this.tableName = tableName;
  33.         index = -1;
  34.     }
  35.     /**
  36.      * 获取结果集总数
  37.      * @return
  38.      */
  39.     private int getCount() {
  40.         return this.dataList.size();
  41.     }
  42.     @Override
  43.     public IMailMergeDataSource getChildDataSource(String arg0)
  44.             throws Exception {
  45.         return null;
  46.     }
  47.     @Override
  48.     public String getTableName() throws Exception {
  49.         return this.tableName;
  50.     }
  51.     /**
  52.      * 实现接口
  53.      * 获取当前index指向数据行的数据
  54.      * 将数据存入args数组中即可
  55.      * @return ***返回false则不绑定数据***
  56.      */
  57.     @Override
  58.     public boolean getValue(String key, Object[] args) throws Exception {
  59.         if(index < 0 || index >= this.getCount()) {
  60.             return false;
  61.         }
  62.         if(args != null && args.length > 0) {
  63.             args[0] = this.dataList.get(index).get(key);
  64.             return true;
  65.         } else {
  66.             return false;
  67.         }
  68.     }
  69.     /**
  70.      * 实现接口
  71.      * 判断是否还有下一条记录
  72.      */
  73.     @Override
  74.     public boolean moveNext() throws Exception {
  75.         index += 1;
  76.         if(index >= this.getCount())
  77.         {
  78.             return false;
  79.         }
  80.         return true;
  81.     }
  82. }

这样我们就把数据填充好了。接下来就是导出了

Java代码  收藏代码
  1. package com.epkj.words;
  2. import javax.servlet.ServletContext;
  3. import javax.servlet.http.HttpServletRequest;
  4. import javax.servlet.http.HttpServletResponse;
  5. import org.springframework.stereotype.Controller;
  6. import org.springframework.web.bind.annotation.RequestMapping;
  7. import org.springframework.web.context.WebApplicationContext;
  8. import org.springframework.web.context.support.WebApplicationContextUtils;
  9. import com.aspose.words.Document;
  10. import com.aspose.words.SaveFormat;
  11. /**
  12.  * 所有导出功能由该类完成
  13.  */
  14. @Controller
  15. @RequestMapping("/DemoBaseController.do")
  16. public class DemoBaseController {
  17.     @RequestMapping(params = "method=exportDoc")
  18.     public Object exportDoc(HttpServletRequest request, HttpServletResponse response) {
  19.         ServletContext sc = request.getSession().getServletContext();
  20.         //加载对应的模板
  21.         String command = request.getParameter("command");
  22.         //下载的文件名
  23.         String docName = request.getParameter("docName");
  24.         if(docName == null) {
  25.             docName = System.currentTimeMillis() + "";
  26.         }
  27.         //返回到客户端的格式(DOC DOCX PDF)
  28.         String formatType = request.getParameter("formatType");
  29.         if(formatType == null) {
  30.             formatType = "DOCX";
  31.         }
  32.         ProcessWord pw = getProcessWordByName(command, sc);
  33.         try {
  34.             Document doc = pw.execute(sc.getRealPath("/Designer"));
  35.             sendToBrowser(doc, docName, formatType, true, response);
  36.             response.flushBuffer();
  37.         } catch (Exception e) {
  38.             throw new RuntimeException(e);
  39.         }
  40.         return null;
  41.     }
  42.     public WebApplicationContext getWebApplicationContext(ServletContext sc) {
  43.         return WebApplicationContextUtils.getRequiredWebApplicationContext(sc);
  44.     }
  45.     private ProcessWord getProcessWordByName(String name, ServletContext sc) {
  46.         return (ProcessWord) this.getWebApplicationContext(sc).getBean(name);
  47.     }
  48.     /**
  49.      * 向客户端发送数据
  50.      * @param doc com.aspose.words.Document
  51.      * @param docName 返回客户端的word文件名
  52.      * @param formatType DOC 或者 DOCX
  53.      * @param openNewWindow 在线打开或者下载
  54.      * @param response
  55.      * @throws Exception
  56.      */
  57.     private void sendToBrowser(Document doc, String docName, String formatType,
  58.             boolean openNewWindow, HttpServletResponse response)
  59.             throws Exception {
  60.         String extension = formatType;
  61.         if (formatType.equals("WML") || formatType.equals("FOPC"))
  62.             extension = "XML";
  63.         String fileName = docName + "." + extension;
  64.         if (openNewWindow)
  65.             response.setHeader("content-disposition", "attachment; filename="
  66.                     + fileName);
  67.         else
  68.             response.addHeader("content-disposition", "inline; filename="
  69.                     + fileName);
  70.         if ("DOC".equals(formatType)) {
  71.             response.setContentType("application/msword");
  72.             doc.save(response.getOutputStream(), SaveFormat.DOC);
  73.         } else if ("DOCX".equals(formatType)) {
  74.             response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
  75.             doc.save(response.getOutputStream(), SaveFormat.DOCX);
  76.         } else if ("PDF".equals(formatType)) {
  77.             response.setContentType("application/pdf");
  78.             doc.save(response.getOutputStream(), SaveFormat.PDF);
  79.         }
  80.     }
  81. }

http://www.iteye.com/topic/1130327

  1. da shang
    donate-alipay
               donate-weixin weixinpay

发表评论↓↓