您的位置:首页 > 编程语言 > ASP

通过Aspose实现文件对象嵌入Word功能

2017-06-29 17:55 696 查看

1. 需求

公司系统更新,需要对历史数据进行附件迁移,将老系统A的附件迁移到新系统B中。其中老系统A的一张单据对应着多个附件,而新系统B要求单据和附件一对一的关系。

偶然间发现可以将文件以对象的方式插入到word中,这样在一个word中就可以浏览到老系统的多个附件。

2. 库的选择

最开始百度啊,使用java操作word的方法,基本上都是poi包。经过搜索和到官网去看并没有发现可以满足需求的操作。接着去Google以下面种种关键字搜索

insert file object in word java
,
Insert Embedded or Linked OLE Object in Word
,
Files embedded OLE objects
找到了Aspose.Words。通过OLE(Object Linking and Embedding)对象链接与嵌入的方式进行文本的合并。

3. 实现

3.1 代码

maven地址

<dependency>
<groupId>com.aspose</groupId>
<artifactId>aspose-barcode</artifactId>
<version>17.03</version>
</dependency>


核心代码

public static void main(String args[]) throws Exception {

PropertyConfigurator.configure("log4j.properties");

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
String MyDir = "C:\\Users\\SN2OV\\Desktop\\wordDemo\\src\\main\\resources\\File\\";
BufferedImage image = ImageIO.read(new File(MyDir + "word32.png"));
String fileArr[] = new String[]{"InsertDocument1.doc","InsertDocument2.doc","其他合同模板.docx","商务标.rar",
"成本模拟部署测试问题-其他所有模块.xls","其他合同模板.doc","乾鸣国际信息产业园(一期)1号楼、8号楼机电安装工程施工-中标通知书.pdf"};
for(String file :fileArr){
if(file.endsWith("png")){
Shape shape = builder.insertImage(MyDir + file);
builder.writeln();
builder.writeln(file);
continue;
}
Shape oleObject = builder.insertOleObject(MyDir + file, false, true, image);
builder.writeln(file);
builder.writeln();
}
doc.save(MyDir + "out.docx");
//清除aspose代理的水印
Utils.deleteWatermark(MyDir + "out.docx");
}


3.2注意事项

3.2.1 Aspose插入和word中直接将文件对象拖入有区别

word原生的插入文件对象图标和文件名是一个整体;而通过Aspose包导入的只能通过人为设置的icon为对象添加图标,同时不能自动显示文件名,需要手动代码添加此功能。



经试验通过Aspose插入的对象文件类型为
.doc .docx .xlsx .xls .pdf .jpg .png
可以有效的打开,
.ppt .pptx
属于office自带的应该也可以。

builder.insertOleObject方法中,第二个参数为isLinked,设置为false才可以将内置文件完全复制进来,设置true则外部文件仅存储内部文件的地址,当地址改变或者文件删除后内部文件无法打开

3.1.2 使用Aspose修改word时会默认加上水印

可以通过其他jar包(比如poi)对该水印进行删除,因为Aspose的水印会自动添加到word的首段,将首段文件进行删除即可去掉水印。

public static void deleteWatermark(String filePath){
XWPFDocument doc = null;//word文档对象
InputStream in_stream = null;
OutputStream _os = null;
try{
in_stream=new FileInputStream(filePath);//文件流
doc=new XWPFDocument(in_stream);
}catch(IOException e){
e.printStackTrace();
}
List<XWPFParagraph> _paraList=doc.getParagraphs();//得到一个包含所有段落的List
XWPFParagraph _p=_paraList.get(0);//获取到第一个段落,根据需要读取相应段落
List<XWPFRun> _runsList=_p.getRuns();//获取段落中的run列表
XWPFRun _run=_runsList.get(0);//获取第一个run对象
String s=_run.getText(0);//获取到run里面的子句字符串
_run.setText(" ",0);//在0位置插入字符串
try{
_os=new FileOutputStream(filePath);
doc.write(_os);
}
catch(IOException e){
e.printStackTrace();
}
try {
in_stream.close();
_os.close();
} catch (IOException e) {
e.printStackTrace();
}
}


4.成果

插入后的效果



对第一个文件双击打开,浏览嵌入的文件



为了方便导附件做个壳



代码地址:http://download.csdn.net/detail/sn2ovfan/9884318

注:
InsertOLE.java
的main函数中要简易的demo(运行时要修改文件路径),其他类涉及数据库的连接、附件迁移等代码,无法直接运行。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java aspose OLE word
相关文章推荐