Java如何操作Word,Excel,PDF文档?
Java Excel API 文档 http://www.andykhan.com/jexcelapi/ 1、一个jacob操作Word的例子,其他操作excel,pdf的sample里都有 import java.io.File; import com.jacob.com.*; import com.jacob.activeX.*; public class WordTest { public static void main(String[] args) { WordBean word=new WordBean(); word.openWord(true); word.createNewDocument(); word.insertText("Hello word."); } } import com.jacob.activeX.*; import com.jacob.com.*; public class WordBean extends java.awt.Panel { private ActiveXComponent MsWordApp = null; private Dispatch document = null; public WordBean() { super(); } public void openWord(boolean makeVisible) { //Open Word if we've not done it already if (MsWordApp == null) { MsWordApp = new ActiveXComponent("Word.Application"); } //Set the visible property as required. Dispatch.put(MsWordApp, "Visible", new Variant(makeVisible)); } public void createNewDocument() { //Find the Documents collection object maintained by Word Dispatch documents = Dispatch.get(MsWordApp,"Documents").toDispatch(); //Call the Add method of the Documents collection to create //a new document to edit document = Dispatch.call(documents,"Add").toDispatch(); } public void insertText(String textToInsert) { // Get the current selection within Word at the moment. If // a new document has just been created then this will be at // the top of the new doc Dispatch selection = Dispatch.get(MsWordApp,"Selection").toDispatch(); //Put the specified text at the insertion point Dispatch.put(selection,"Text",textToInsert); } public void saveFileAs(String filename) { Dispatch.call(document,"SaveAs",filename); } public void printFile() { //Just print the current document to the default printer Dispatch.call(document,"PrintOut"); } public void closeDocument() { // Close the document without saving changes // 0 = wdDoNotSaveChanges // -1 = wdSaveChanges // -2 = wdPromptToSaveChanges Dispatch.call(document, "Close", new Variant(0)); document = null; } public void closeWord() { Dispatch.call(MsWordApp,"Quit"); MsWordApp = null; document = null; } }
java解析word文档有哪些方法
java读取word文档时,虽然网上介绍了很多插件poi、java2Word、jacob、itext等等,poi无法读取格式(新的API估计行好像还在处于研发阶段,不太稳定,做项目不太敢用);java2Word、jacob容易报错找不到注册,比较诡异,我曾经在不同的机器上试过,操作方法完全一致,有的机器不报错,有的报错,去他们论坛找高人解决也说不出原因,项目部署用它有点玄;itxt好像写很方便但是我查了好久资料没有见到过关于读的好办法。
经过一番选择还是折中点采用rtf最好,毕竟rtf是开源格式,不需要借助任何插件,只需基本IO操作外加编码转换即可。
rtf格式文件表面看来和doc没啥区别,都可以用word打开,各种格式都可以设定。
----- 实现的功能:读取rtf模板内容(格式和文本内容),替换变化部分,形成新的rtf文档。
----- 实现思路:模板中固定部分手动输入,变化的部分用$info$表示,只需替换$info$即可。
1、采用字节的形式读取rtf模板内容2、将可变的内容字符串转为rtf编码3、替换原文中的可变部分,形成新的rtf文档主要程序如下:public String bin2hex(String bin) {char[] digital = "0123456789ABCDEF".toCharArray();StringBuffer sb = new StringBuffer("");byte[] bs = bin.getBytes();int bit;for (int i = 0; i > 4;sb.append("\\'");sb.append(digital[bit]);bit = bs[i] & 0x0f;sb.append(digital[bit]);}return sb.toString(); }public String readByteRtf(InputStream ins, String path){ String sourcecontent =""; try{ ins = newFileInputStream(path); byte[] b= new byte[1024];if (ins == null) {System.out.println("源模板文件不存在");}int bytesRead = 0;while (true) {bytesRead = ins.read(b, 0, 1024); // return final read bytescountsif(bytesRead == -1) {// end of InputStreamSystem.out.println("读取模板文件结束");break;}sourcecontent += new String(b, 0, bytesRead); // convert to stringusing bytes} }catch(Exception e){ e.printStackTrace(); } return sourcecontent ;}以上为核心代码,剩余部分就是替换,从新组装java中的String.replace(oldstr,newstr);方法可以实现,在这就不贴了。
源代码部分详见附件。
运行源代码前提:c盘创建YQ目录,将附件中"模板.rtf"复制到YQ目录之下,运行OpreatorRTF.java文件即可,就会在YQ目录下生成文件名如:21时15分19秒_cheney_记录.rtf的文件。
package com;import java.io.File;import java.io.FileInputStream;import java.io.FileWriter;import java.io.IOException;import java.io.InputStream;import java.io.PrintWriter;import java.text.SimpleDateFormat;import java.util.Date;public class OperatorRTF {public String strToRtf(String content){char[] digital = "0123456789ABCDEF".toCharArray();StringBuffer sb = new StringBuffer("");byte[] bs = content.getBytes();int bit;for (int i = 0; i > 4;sb.append("\\'");sb.append(digital[bit]);bit = bs[i] & 0x0f;sb.append(digital[bit]);}return sb.toString();}public String replaceRTF(String content,String replacecontent,intflag){String rc = strToRtf(replacecontent);String target = "";if(flag==0){target = content.replace("$timetop$",rc);}if(flag==1){target = content.replace("$info$",rc);}if(flag==2){target = content.replace("$idea$",rc);}if(flag==3){target = content.replace("$advice$",rc);}if(flag==4){target = content.replace("$infosend$",rc);}return target;}public String getSavePath() {String path = "C:\\YQ";File fDirecotry = new File(path);if (!fDirecotry.exists()) {fDirecotry.mkdirs();}return path;}public String ToSBC(String input){char[] c =input.toCharArray();for (int i =0; i < c.length; i++){if (c[i] == 32){c[i] = (char) 12288;continue;}if (c[i] < 127){c[i] = (char) (c[i] + 65248);}}return newString(c);}public void rgModel(String username, String content) {// TODO Auto-generated method stubDate current=new Date();SimpleDateFormat sdf=new java.text.SimpleDateFormat("yyyy-MM-ddHH:mm:ss");String targetname = sdf.format(current).substring(11,13) + "时";targetname += sdf.format(current).substring(14,16) + "分";targetname += sdf.format(current).substring(17,19) + "秒";targetname += "_" + username +"_记录.rtf";String strpath = getSavePath();String sourname = strpath+"\\"+"模板.rtf";String sourcecontent = "";InputStream ins = null;try{ins = new FileInputStream(sourname);byte[] b = new byte[1024];if (ins == null) {System.out.println("源模板文件不存在");}int bytesRead = 0;while (true) {bytesRead = ins.read(b, 0, 1024); // return final read bytescountsif(bytesRead == -1) {// end of InputStreamSystem.out.println("读取模板文件结束");break;}sourcecontent += new Strin...
java操作word 的有哪几种方式
java读取word文档时,虽然网上介绍了很多插件poi、java2Word、jacob、itext等等,poi无法读取格式(新的API估计行好像还在处于研发阶段,不太稳定,做项目不太敢用);java2Word、jacob容易报错找不到注册,比较诡异,我曾经在不同的机器上试过,操作方法完全一致,有的机器不报错,有的报错,去他们论坛找高人解决也说不出原因,项目部署用它有点玄;itxt好像写很方便但是我查了好久资料没有见到过关于读的好办法。
经过一番选择还是折中点采用rtf最好,毕竟rtf是开源格式,不需要借助任何插件,只需基本IO操作外加编码转换即可。
rtf格式文件表面看来和doc没啥区别,都可以用word打开,各种格式都可以设定。
----- 实现的功能:读取rtf模板内容(格式和文本内容),替换变化部分,形成新的rtf文档。
----- 实现思路:模板中固定部分手动输入,变化的部分用$info$表示,只需替换$info$即可。
1、采用字节的形式读取rtf模板内容2、将可变的内容字符串转为rtf编码3、替换原文中的可变部分,形成新的rtf文档主要程序如下:public String bin2hex(String bin) {char[] digital = "0123456789ABCDEF".toCharArray();StringBuffer sb = new StringBuffer("");byte[] bs = bin.getBytes();int bit;for (int i = 0; i > 4;sb.append("\\'");sb.append(digital[bit]);bit = bs[i] & 0x0f;sb.append(digital[bit]);}return sb.toString(); }public String readByteRtf(InputStream ins, String path){ String sourcecontent =""; try{ ins = newFileInputStream(path); byte[] b= new byte[1024];if (ins == null) {System.out.println("源模板文件不存在");}int bytesRead = 0;while (true) {bytesRead = ins.read(b, 0, 1024); // return final read bytescountsif(bytesRead == -1) {// end of InputStreamSystem.out.println("读取模板文件结束");break;}sourcecontent += new String(b, 0, bytesRead); // convert to stringusing bytes} }catch(Exception e){ e.printStackTrace(); }
怎样才能把word文件读取并显示在java中?请各位指教!
经过一番选择还是折中点采用rtf最好,毕竟rtf是开源格式java读取word文档时,虽然网上介绍了很多插件poi,各种格式都可以设定、java2Word,不需要借助任何插件,去他们论坛找高人解决也说不出原因,项目部署用它有点玄;itxt好像写很方便但是我查了好久资料没有见到过关于读的好法,操作方法完全一致,有的机器不报错,有的报错,比较诡异,我曾经在不同的机器上试过,做项目不太敢用);java2Word、jacob容易报错找不到注册,poi无法读取格式(新的API估计行好像还在处于研发阶段,不太稳定、itext等等、jacob,只需基本IO操作外加编码转换即可。
rtf格式文件表面看来和doc没啥区别,都可以用word打开。
具体代码可以参考:/...
java操作word文件有什么好的方法
1-apache的POI,此方法对Excel的导出做的很好,目前对Word的导出方面的功能尚未完全。
2-纯JavaScript脚本实现。
主要通过客户端调用本机Office组件来实现。
3-在JSP页面引入头文件实现。
纯JavaScript脚本实现细节方面大体是创建一个word组件ActiveXObject('Word.Application'),用js通过表ID取得表内容然后保存到word,要注意的是js实现有很多不好的地方,例如Internet选项需要把ActiveX空间全部启用,安全级别设置为中。
这样的话岂不是每台机器都要配置一下。
其次每次生成word文档以后弹出对话框(无法保存此文件,因为它已在别处打开(C:\...\STARTUP\Powerword.dot)),出现此问题就需要把C:\Documents and Settings\当前用户名\Application Data\Microsoft\Word\STARTUP下的Powerword.dot文件删除,每次遇到此问题就需要删除文件来解决,十分不方便。
JSP页面引入来实现Word保存就方便多了,但是也有不足的地方,首先如果需要引入如果需要下载的话就引入其实如果大家用框架做就方便多了,比如Struts2。
在Action里直接写如下代码:if(out!=null){String fileName="";fileName+="评价报告.doc";try {HttpServletResponse response = ServletActionContext.getResponse();response.setHeader("Content-disposition","attachment; filename="+new String(fileName.getBytes("GB2312"), "8859_1"));} catch (UnsupportedEncodingException e) {e.printStackTrace();}out是jsp页面表单元素,一个button,用于提交表单到相应Action进行Word下载。
Action设置jsp页面头文件。
这样每次点击button就可以把相应jsp页面的内容保存到Word中并且支持下载,Word中内容并且是可编辑状态。
不足的地方在于由于表内容是动态生成,有的需要先查看在下载Word,就需要另外建立一个新JSP页面进行Word下载,当然首先要在struts.xml里配置好页面转向。
新建立的页面传值同查看页面要保持一样。
如何利用Java
1. 初始化com的线程,非常重要,否则第二次创建com对象的时候会出现can't co-create object异常 (参见jacob的帮助文档),完成操作com组件后要调用 realease方法 ComThread.InitSTA();// 初始化com的线程,非常重要!!使用结束后要调用 realease方法 2. 初始化word应用程序,新建一个空白文档,取得文档内容对象//Instantiate objWord //Declare word object ActiveXComponent objWord = new ActiveXComponent("Word.Application"); //Assign a local word object Dispatch wordObject = (Dispatch) objWord.getObject(); //Create a Dispatch Parameter to show the document that is opened Dispatch.put((Dispatch) wordObject, "Visible", new Variant(true));// new Variant(true)表示word应用程序可见 Tip:设置一个对象的属性的时候,利用Dispatch的put方法,给属性赋值。
上面这行语句相当于vb的 wordObject.Visible = true 语句 //Instantiate the Documents Property Dispatch documents = objWord.getProperty("Documents").toDispatch(); //documents表示word的所有文档窗口,(word是多文档应用程序) //Add a new word document, Current Active Document Dispatch document = Dispatch.call(documents, "Add").toDispatch(); // 使用Add命令创建一个新文档,用Open命令可以打开一个现有文档 Tip:调用一个对象的方法的时候,利用Dispatch的call方法,上面的语句相当于vb的document = documents.Add() 语句。
Dispatch wordContent = Dispatch.get(document, "Content").toDispatch(); // 取得word文件的内容 Tip:取得一个对象的成员变量(属性)时利用Dispatch的get方法,上面的语句相当于vb的wordContent = document.Content语句 3. 取得word文档的内容后,可以对其内容进行操作 Dispatch.call(wordContent, "InsertAfter", "这里是一个段落的内容");//插入一个段落 4. 设置刚插入的段落的文字格式 Dispatch paragraphs = Dispatch.get(wordContent, "Paragraphs").toDispatch(); // 所有段落 int paragraphCount = Dispatch.get(paragraphs, "Count").toInt(); // 一共的段落数 // 找到刚输入的段落,设置格式 Dispatch lastParagraph = Dispatch.call(paragraphs, "Item", new Variant(paragraphCount)). toDispatch(); // 最后一段 Dispatch lastParagraphRange = Dispatch.get(lastParagraph, "Range"). toDispatch(); Dispatch font = Dispatch.get(lastParagraphRange, "Font").toDispatch(); Dispatch.put(font, "Bold", new Variant(true)); // 设置为黑体 Dispatch.put(font, "Italic", new Variant(true)); // 设置为斜体 Dispatch.put(font, "Name", new Variant("宋体")); // Dispatch.put(font, "Size", new Variant(12)); //小四 注意:如果想插入一个新的空白行,也需要设置段落的文字格式,否则新插入行的文字格式会于刚插入的段落的格式相同。
5. 将当前文档保存 Dispatch.call(document, "SaveAs", new Variant("C: abc.doc")); // 保存一个新文档 6. 释放COM线程 ComThread.Release();//释放com线程。
根据jacob的帮助文档,com的线程回收不由java的垃圾回收器处理 完整测试代码:(StudyJacob.java 附件中有本文章和java源文件) import com.jacob.activeX.ActiveXComponent; import com.jacob.com.Dispatch; import com.jacob.com.Variant; import com.jacob.com.ComThread; public class StudyJacob { public static void main(String[] args) { ComThread.InitSTA();// 初始化com的线程,非常重要!!使用结束后要调用 realease方法 //Instantiate objWord //Declare word object ActiveXComponent objWord = new ActiveXComponent("Word.Application"); //Assign a local word object Dispatch wordObject = (Dispatch) objWord.getObject(); //Create a Dispatch Parameter to show the document that is opened Dispatch.put((Dispatch) wordObject, "Visible", new Variant(true));// new Variant(true)表示word应用程序可见 //Instantiate the Documents Property Dispatch documents = objWord.getProperty("Documents").toDispatch(); //documents表示word的所有文档窗口,(word是多文档应用程序) //Add a new word document, Current Active Document Dispatch document = Dispatch.call(documents, "Add").toDispatch(); // 使用Add命令创建一个新文档,用Open命令可以打开一个现有文档 Dispatch wordContent = Dispatch.get(document, "Content").toDispatch(); // 取得word文件的内容 Dispatch.call(wordContent, "InsertAfter", "这里是一个段落的内容");//插入一个段落 Dispatch paragraphs = Dispatch.get(wordContent, "Paragraphs").toDispatch(); // 所有段落 int paragraphCount = Dispatch.get(paragraphs, "Count").toInt(); // 一共的段落数 // 找到刚输入的段落,设置格式 Dispatch lastParagraph = Dispatch.call(paragraphs, "Item", new Variant(paragraphCount)). toDispatch(); // 最后一段 ...
求救:用java填写word模板的方法。
如何使用JAVA、POI读写word文档??能不能将一个word的内容完全读过来,放到一个新生成的word文件中去,要求能将word中的表格、图片等保留,格式不变。
最好能给个例子?网上多是很早以前的那个解决方法如下:,只能读文本内容,且新生成的word文件打开时总是要提示选择编码,不太好用,希望能有新的解决方案??!!poi操作word1.1 添加poi支持:包下载地址1.2 POI对Excel文件的读取操作比较方便,POI还提供对Word的DOC格式文件的读取。
但在它的发行版本中没有发布对Word支持的模块,需要另外下载一个POI的扩展的Jar包。
下载地址为;下载extractors-0.4_zip这个文件2、提取Doc文件内容 public static String readDoc(String doc) throws Exception {// 创建输入流读取DOC文件 FileInputStream in = new FileInputStream(new File(doc)); WordExtractor extractor = null; String text = null;// 创建WordExtractor extractor = new WordExtractor();// 对DOC文件进行提取 text = extractor.extractText(in); return text; } public static void main(String[] args) { try{ String text = WordReader.readDoc("c:/test.doc"); System.out.println(text); }catch(Exception e){ e.printStackTrace(); } }3、写入Doc文档 import java.io.ByteArrayInputStream; import java.io.FileOutputStream; import java.io.IOException; import org.apache.poi.poifs.filesystem.DirectoryEntry; import org.apache.poi.poifs.filesystem.DocumentEntry; import org.apache.poi.poifs.filesystem.POIFSFileSystem; public class WordWriter { public static boolean writeDoc(String path, String content) { boolean w = false; try { // byte b[] = content.getBytes("ISO-8859-1"); byte b[] = content.getBytes(); ByteArrayInputStream bais = new ByteArrayInputStream(b); POIFSFileSystem fs = new POIFSFileSystem(); DirectoryEntry directory = fs.getRoot(); DocumentEntry de = directory.createDocument("WordDocument", bais); FileOutputStream ostream = new FileOutputStream(path); fs.writeFilesystem(ostream); bais.close(); ostream.close(); } catch (IOException e) { e.printStackTrace(); } return w; } public static void main(String[] args) throws Exception{ String wr=WordReader.readDoc("D:\\test.doc"); boolean b = writeDoc("D:\\result.doc",wr);
怎样用java将特定的数据写入特定word文档中的特定位
使用Java操作word的方法有几个,列出来:IText,Apache的POI包,tm-extractors包,jacob包,java2word包。
IText包比较大,但是功能比较全。
而且比较成熟,用的人也多。
POI包是Apache的一个项目,不过现在已经停止更新了,而且我看了里面的Example,感觉调用起来很麻烦。
用过之后再也不想用了。
tm-extractors包的API比较简单,调用起来很方便,代码量也少。
jacob包我觉得是最强大的,可以操作word,excel。
因为调用的是微软底层的dll文件,需要在system32目录下放置jacob.dll,然后在classpath里面添加jacob.jar文件。
推荐使用1.9版本,之前1.8版本调用起来就算你的代码没有写错也会出现一些莫名其妙的异常。
java2word也是调用微软的底层dll文件,有安装包,也有解压包,安装包会将jacob.dll文件装在system32目录下。
之后将java2word.jar加到classpath就可以使用了。
感觉如果只是操作word文档的话,比jacob用起来要简单和舒服。
代码量也少,很清晰。
另外,使用jacob和java2word的话,会在调用WINWORD进程,如果多人并发访问服务器的word文件的话,会造成内存不足。
转载请注明出处51数据库 » java2word 使用说明