JAVA 使用Aspose.Words组件生产Word或PDF文件

来源:互联网 发布:mysql 登录失败设置 编辑:程序博客网 时间:2024/06/06 00:32

一、配置环境(这是我自己的环境配置)

1、JDK1.6

2、Aspose.Words.jdk15.jar 或者 Aspose.Words.jdk15.jar 包

3、自己创建一个Word模板文件,如图:


其中划红线的地方是添加单个数据的划紫线的地方是添加多个数据的,能循环添加。红线和紫线的地方都是Word文档中的域。

4、这个文件也不能缺少(有可能不用,但我没试过),要通过它支持Aspose.Words。

二、示例代码

1、首先要实现 IMailMergeDataSource 接口

<span style="font-size:12px;">package com.qian.word.content;import java.util.ArrayList;import java.util.List;import java.util.Map;import com.aspose.words.IMailMergeDataSource;/** * 封装循环实体,实体用map进行分装 * @author zoushidong *--@deprecated  没有直接封装实体有用(已弃用)(已做修改) */public class MapListDataSource implements IMailMergeDataSource  {private List<Map<String, Object>> dataList;          private int index;            //word模板中的    private String tableName = null;            /**      * @param dataList 数据集      * @param tableName 与模板中的Name对应      */      public MapListDataSource(List<Map<String, Object>> dataList, String tableName) {          this.dataList = dataList;          this.tableName = tableName;          index = -1;      }            /**      * @param data 单个数据集      * @param tableName 与模板中的Name对应      */      public MapListDataSource(Map<String, Object> data, String tableName) {          if(this.dataList == null) {              this.dataList = new ArrayList<Map<String,Object>>();              this.dataList.add(data);          }          this.tableName = tableName;          index = -1;      }               /**      * 获取结果集总数      * @return      */      private int getCount() {          return this.dataList.size();      }                 public String getTableName() throws Exception {          return this.tableName;      }        /**      * 实现接口      * 获取当前index指向数据行的数据      * 将数据存入args数组中即可      * @return ***返回false则不绑定数据***      */      public boolean getValue(String key, Object[] args) throws Exception {          if(index < 0 || index >= this.getCount()) {              return false;          }          if(args != null && args.length > 0) {              args[0] = this.dataList.get(index).get(key);              return true;          } else {              return false;          }      }        /**      * 实现接口      * 判断是否还有下一条记录      */      @Override      public boolean moveNext() throws Exception {          index += 1;          if(index >= this.getCount())          {              return false;          }          return true;      }@Overridepublic IMailMergeDataSource getChildDataSource(String arg0)throws Exception {// TODO Auto-generated method stubreturn null;}  }</span>

2、加载Aspose.Words.lic

<span style="font-size:12px;">/** * 添加Aspose.Word许可认证文件 */static {try {License license = new License();license.setLicense(URLDecoder.decode(BasicWordController.class.getResource("Aspose.Words.lic").getFile(), "UTF-8")); //这是加载Aspose.Words.licif (System.getProperty("os.name").toLowerCase().indexOf("windows") == -1&& System.getProperty("os.name").toLowerCase().indexOf("mac") == -1) {// 在linux下加载字体库FontSettings.setFontsFolder("//usr//share//fonts", true);}} catch (Exception e) {e.printStackTrace();throw new RuntimeException(e.getMessage());}}</span>

3、Aspose.Words貌似只能保存List<Map<String, Object>>的类型,不能保存List集合。(至少我知道的是这样,如果有谁知道怎么把List集合加载到Word文档中,请告知)

<span style="font-size:12px;">//建立数据集合private static List<Map<String, Object>> getMapList(String imagePath) throws Exception{List<Map<String, Object>> dataList = new ArrayList<Map<String,Object>>();//读取一个二进制图片  FileInputStream fis = new FileInputStream(imagePath);  byte[] image = new byte[fis.available()];  fis.read(image);  fis.close(); for (int i = 0; i < 20; i++) {  Map<String, Object> record = new HashMap<String, Object>();  //这里的key要与模板中的<<xxxxx>>对应  record.put("lineNo", i);  record.put("personName", "夏丹");  record.put("sexName", "男");  record.put("age", "20");  record.put("companyName", "美髯公"); //二进制数据  record.put("img", image);  record.put("mobile", "13051292503");record.put("academician", "测试成功"); dataList.add(record);  }  return dataList;}</span>

4、测试
<span style="font-size:12px;">package com.qian.word;import java.io.ByteArrayOutputStream;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.OutputStream;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import com.aspose.words.BreakType;import com.aspose.words.Document;import com.aspose.words.DocumentBuilder;import com.aspose.words.SaveFormat;import com.aspose.words.StyleIdentifier;import com.qian.word.content.MapListDataSource;public class TestWriteWord {public static void main(String[] args) throws Exception {//获取模板路径String doctpl = TestWriteWord.class.getResource("wordfile/")+"";//获取到的路径是:file://E....所以需要截取doctpl=doctpl.substring(6);String imagePath = doctpl+"ani.jpg";System.out.println(doctpl);System.out.println(imagePath);test1(doctpl);}/** * 使用Word模板,把数据导入到模板中,然后重新写入另外新的Word文档 * @param doctpl * @throws Exception  */private static void test1(String doctpl) throws Exception{//创建Document对象,读取Word模板Document doc = new Document(doctpl + "tpl.doc");String imagePath = doctpl+"ani.jpg";//向模板填充数据源doc.getMailMerge().executeWithRegions(new MapListDataSource(getMapList(imagePath), "expert"));//填充单个数据doc.getMailMerge().execute(new String[]{"judgeGroupName","projectCount"}, new String[]{"很好","10"});//写入到Word文档中ByteArrayOutputStream os = new ByteArrayOutputStream();//保存到输出流中doc.save(os, SaveFormat.DOC);OutputStream out = new FileOutputStream("show.doc");out.write(os.toByteArray());out.close();}}</span>


0 0