1.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 < bs.length;i++)="" {bit="(bs[i]" &="" 0x0f0)="">> 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 < bs.length;="" i++)="" {bit="(bs[i]" &="" 0x0f0)="">> 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">
2.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 bit = (bs[i] & 0x0f0)>> 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 = new FileInputStream(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 bytes counts if(bytesRead == -1) {// end of InputStream System.out.println("读取模板文件结束"); break; } sourcecontent += new String(b, 0, bytesRead); // convert to string using 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 bit = (bs[i] & 0x0f0)>> 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,int flag){ 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 if (c[i] == 32){ c[i] = (char) 12288; continue; } if (c[i] c[i] = (char) (c[i] + 65248); } } return new String(c); } public void rgModel(String username, String content) {// TODO Auto-generated method stub Date current=new Date(); SimpleDateFormat sdf=new java.text.SimpleDateFormat("yyyy-MM-dd HH: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 bytes counts if(bytesRead == -1) {// end of InputStream System.out.println("读取模板文件结束"); break; } sourcecontent += new String(b, 0, bytesRead); // convert to string using bytes } }catch(Exception e){ e.printStackTrace(); } String targetcontent = ""; String array[] = content.split("~"); for(int i=0;i if(i==0){ targetcontent = replaceRTF(。
3.使用Java操作文本文件的方法有哪些呢
最初Java是不支持对文本文件的处理的,为了弥补这个缺憾而引入了Reader和Writer两个类,这两个类都是抽象类,Writer中write(char[] ch,int off,int length),flush()和close()方法为抽象方法,Reader中read(char[] ch,int off,int length)和close()方法是抽象方法。
子类应该分别实现他们。 当我们读写文本文件的时候,采用Reader是非常方便的,比如FileReader,InputStreamReader和BufferedReader。
其中最重要的类是InputStreamReader,它是字节转换为字符的桥梁。 你可以在构造器重指定编码的方式,如果不指定的话将采用底层操作系统的默认编码方式,例如GBK等。
当使用FileReader读取文件的时候。 FileReader fr = new FileReader("ming。
txt"); int ch = 0; while((ch = fr。 read())!=-1 ) { System。
out。print((char)ch); } 其中read()方法返回的是读取得下个字符。
当然你也可以使用read(char[] ch,int off,int length)这和处理二进制文件的时候类似,不多说了。 如果使用InputStreamReader来读取文件的时候 while((ch = isr。
read())!=-1) { System。out。
print((char)ch); } 这和FileReader并没有什么区别,事实上在FileReader中的方法都是从InputStreamReader中继承过来的。 read()方法是比较好费时间的,如果为了提高效率我们可以使用BufferedReader对Reader进行包装,这样可以提高读取得速度,我们可以一行一行的读取文本,使用readLine()方法。
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("ming。 txt"))); String data = null; while((data = br。
readLine())!=null) { System。out。
println(data); } 当你明白了如何用Reader来读取文本文件的时候那么用Writer写文件同样非常简单。 有一点需要注意,当你写文件的时候,为了提高效率,写入的数据会先放入缓冲区,然后写入文件。
因此有时候你需要主动调用flush()方法。与上面对应的写文件的方法为: FileWriter fw = new FileWriter("hello。
txt"); String s = "hello world"; fw。 write(s,0,s。
length()); fw。flush(); OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("hello2。
txt")); osw。 write(s,0,s。
length()); osw。flush(); PrintWriter pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream("hello3。
txt")),true); pw。println(s);。
4.Java7中如何对文件进行操作
这篇文件是以你对Java7里提供的新的Path类很熟悉为前提,如果你不熟悉这个类,这里就简单说一句, Path 是文件系统里对位置的一个逻辑概念,例如 c: 和 /foobar。
txt 都是Path。 创建和删除文件 下面的代码片段向你展示的是用 Files。
createFile(Path target) 方法创建文件的基本用法。 1。
Path target = Paths。get("D:\Backup\MyStuff。
txt"); 2。 Path file = Files。
createFile(target); 很多时候,出于安全的原因,你可能希望在创建的文件上设置一下属性,例如:是否可读/可写/写执行。 这些属性依赖于文件系统的种类,你需要使用跟文件系统相应的权限辅助类来完成这种操作。
例如,PosixFilePermission和PosixFilePermissions 为 POSIX 文件系统设计的。下面的是在POSIX文件系统上的文件设置读写权限的用法。
1。Path target = Paths。
get("D:\Backup\MyStuff。txt"); 2。
Set perms= PosixFilePermissions。fromString("rw-rw-rw-"); 3。
FileAttribute。
5.如何在java中操作word
想用java操作word文件?jacob是个不错的选择,也就是java-com桥,你可以在.jacob.activeX改为com.test.jacob.activeX,把com.jacob.com改为com.test.jacob.com,打包时只有这两个包是有用的,所以只改它们就够了。 (2)然后修改build.xml中src.java.jacob.mainpackage的value为com.test.jacob,修改java.class.main的value为com.test.jacob.com.Jacob。
(3)别忘了javaJarBin中打包的源码路径也要改,改为。 (4)build.xml中对生成的dll和jar包也要改个名,比如我们把这两个文件改为jacob_test.dll和jacob_test.jar。
修改build.xml中的enerated.filename.dll和generated.filename.jar的value为你新改的名字。 (5)com.test.jacob.com.LibraryLoader中,System.loadLibrary("jacob");改成System.loadLibrary("jacob_test"); (6)另外,很重要的,在jni中*.cpp和*.h中com_jacob_com统一改为com_test_jacob_com,com/jacob/com统一改为com/test/jacob/com。
(7)ant编译,编译好的文件在release目录下。 (8)最后把编译好的jacob_test.dll文件放在windows/system32下就大功告成了。
现在该用到jacob.jar了,如果你自己修改过jar包的名字,用新改的jar包,如jacob_test.jar,这里统一称为jacob.jar。 首先在classpath中引入jacob.jar包,如果是web应用,WEB-INF的lib中也要加入jacob.jar包。
下面给一个例子: 类ReplaceWord.java import com.jacob.com.*; import com.jacob.activeX.*; public class ReplaceWord { public static void main(String[] args) { ActiveXComponent app = new ActiveXComponent("Word.Application"); //启动word String inFile = "C:\\test.doc"; //要替换的word文件 try { app.setProperty("Visible", new Variant(false)); //设置word不可见 Dispatch docs = app.getProperty("Documents").toDispatch(); Dispatch doc = Dispatch.invoke(docs,"Open",Dispatch.Method,new Object[] { inFile, new Variant(false),new Variant(false) }, new int[1]).toDispatch(); //打开word文件,注意这里第三个参数要设为false,这个参数表示是否以只读方式打开,因为我们要保存原文件,所以以可写方式打开。 Dispatch selection=app.getProperty("Selection").toDispatch();//获得对Selection组件 Dispatch.call(selection, "HomeKey", new Variant(6));//移到开头 Dispatch find = Dispatch.call(selection, "Find").toDispatch();//获得Find组件 Dispatch.put(find, "Text", "name"); //查找字符串"name" Dispatch.call(find, "Execute"); //执行查询 Dispatch.put(selection, "Text", "张三"); //替换为"张三" Dispatch.call(doc, "Save"); //保存 Dispatch.call(doc, "Close", new Variant(false)); } catch (Exception e) { e.printStackTrace(); } finally { app.invoke("Quit", new Variant[] {}); app.safeRelease(); } } } 也许你会问,我怎么知道要调用哪个方法传哪些参数来进行操作?别忘了,word还有宏呢!自己录制一个宏,编辑这个宏就可以看到代码了!用哪个对象的哪个方法就看你的了。
我总结了一下: document下的组件都用Dispatch selection=app.getProperty("Selection").toDispatch()这种方法获得; 再往下的组件就需要调用selection的方法来获取,如 Dispatch find = Dispatch.call(selection, "Find").toDispatch(); 如果某个方法需要参数,Dispatch doc = Dispatch.invoke(docs,"Open",Dispatch.Method,new Object[] { inFile, new Variant(false),new Variant(false) }, new int[1]).toDispatch()是一个例子,这是调用docs的Open方法,Object[]数组里就是它需要的参数了; 如果要修改某个组件的属性呢,用Dispatch.put(find, "Text", "name")这种形式,"Text"是属性名,"name"是值。
6.Java如何操作Word?Java如何操作Word,Excel,
Java Excel API 文档 /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; } }。
7.JAVA读取WORD,EXCEL,PDF文件的方法是什么呢
JAVA读取WORD,EXCEL,POWERPOINT,PDF文件的方法 OFFICE文档使用POI控件,PDF可以使用PDFBOX0。
7。3控件,完全支持中文,用XPDF也行,不过感觉PDFBOX比较好,而且作者也在更新。
水平有限,万望各位指正 WORD: import org。 apache。
lucene。document。
Document; import org。apache。
lucene。document。
Field; import org。apache。
poi。hwpf。
extractor。WordExtractor; import java。
io。File; import java。
io。InputStream; import java。
io。FileInputStream; import com。
search。code。
Index; public Document getDocument(Index index, String url, String title, InputStream is) throws DocCenterException { String bodyText = null; try { WordExtractor ex = new WordExtractor(is);//is是WORD文件的InputStream bodyText = ex。 getText(); if(!bodyText。
equals("")){ index。AddIndex(url, title, bodyText); } }catch (DocCenterException e) { throw new DocCenterException("无法从该Mocriosoft Word文档中提取内容", e); }catch(Exception e){ e。
printStackTrace(); } } return null; } Excel: import org。apache。
lucene。document。
Document; import org。apache。
lucene。 document。
Field; import org。apache。
poi。hwpf。
extractor。WordExtractor; import org。
apache。poi。
hssf。usermodel。
HSSFWorkbook; import org。 apache。
poi。hssf。
usermodel。HSSFSheet; import org。
apache。poi。
hssf。usermodel。
HSSFRow; import org。apache。
poi。hssf。
usermodel。 HSSFCell; import java。
io。File; import java。
io。InputStream; import java。
io。FileInputStream; import com。
search。code。
Index; public Document getDocument(Index index, String url, String title, InputStream is) throws DocCenterException { StringBuffer content = new StringBuffer(); try{。
8.用java打开一个word文档(a.docx) 怎么搞
package cn.rain.main;
import java.io.File;
import java.io.IOException;
public class TT {
/**
* @param args
*/
public static void main(String[] args) {
try {
Runtime.getRuntime().exec("C:\\Program Files\\Microsoft Office\\OFFICE11\\WINWORD.EXE aa.doc");
} catch (IOException e) {
// TODO 自动生zhidao成 catch 块
e.printStackTrace();
}
}
}
你的WORD安装路径C:\\Program Files\\Microsoft Office\\OFFICE11\\WINWORD.EXE空格后所加的aa.doc为你的文档文件名(有文件名重复专的,可以加路径,写法和安装路径的写法一样)
或者用属Runtime.getRuntime().exec("cmd /c \"C:\\temp\\the list.doc\"");
也可以运行
转载请注明出处51数据库 » java对word文件的操作方法