/** * This is the basic class to operate office files by Java, it's not suggested * to use itself.Please use the classes derived from it. * * @filename: Convertor.java * @author Me */ package***.***.system.document;
import com.heavenlake.wordapi.Document;
importjava.io.File; importjava.util.List;
publicclass Convertor{ Documentdoc=null;
//DocumentLock dl = new DocumentLock( ); //加锁操作会与word程序本身的文件锁冲突
if(!this.close( false)){ System.err.println("Error occured when close the file:" + strFileName); }
returnnull; }// end catch
}
publicbooleanclose(boolean bSave){ if(null!=doc){ // try to close
try{ doc.close( bSave); return true; } // if close failed
catch(Exception e1){ // if bSave = true( means tried to close with save failed)
if( bSave){ // try to close without save
try{ if(null!=doc){ doc.close(!bSave); } } // try to close without save failed
catch(Exception e){ e.printStackTrace(); }// end inner try
}// end inner if
System.err.println("The operation Close Failed (document id:" +doc.toString()); }// end outer try
finally { //dl.release( );
} } return false; }
/** * Copy a word's document from a template(not *.dot, but *.doc) * * @param from: * the template file * @param to: * the target file * @return: result of the copy operation */ publicbooleancopy(Stringfrom,String to) { if(null==from||"".equals(from)||null== to ||"".equals( to)) { return false; }
// 简单的复制操作。对副本进行插入动作,保证原word文档不因插入操作失败而被损坏
return CopyFile.copyFile(from, to); }
/** * insert data into the place identified by bookmarks * * @param file: * target file * @param bookmark: * List of bookmarks * @param data: * List of data * @return result of the Insert operation */ publicboolean conv(Stringfile,List<String> bookmark,List<String> data) { if( bookmark.size()!= data.size()) { System.err.println("The count differs ("+file +":bookmark and data)"); return false; }
booleanresult= false;
//Document doc = this.open( file);
if(null==doc) { returnresult; } // open file and insert
try { result= true; for(int i = 0; i < bookmark.size(); i++) { // when exception occurs, continue with the section FOR
try { doc.insertAtBookmark( bookmark.get( i), data.get( i)); } catch(Exception e) { System.err.println("data insert failed (index:" +String.valueOf( i)+")"); result= false; continue; } } } catch(Exception e1) { System.err.println("Open file failed when trying to insert data:" +file); // close the file