读写word文件的class|Java中如何用I/O流读取一个Word文档的内容

|

① java有什么好的方法可以将word里的文本读取出来

你用免费版的Free Spire.Doc for Java可以直接读取Word文档里面的文本,参考代码:

import com.spire.doc.Document;

import java.io.FileWriter;

import java.io.IOException;

public class ExtractText {

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

//加载Word文档

Document document = new Document();

document.loadFromFile("C:\Users\Administrator\Desktop\sample.docx");

//获取文档中的文本保存为String

String text=document.getText();

//将String写入Txt文件

writeStringToTxt(text,"ExtractedText.txt");

}

public static void writeStringToTxt(String content, String txtFileName) throws IOException {

FileWriter fWriter= new FileWriter(txtFileName,true);

try {

fWriter.write(content);

}catch(IOException ex){

ex.printStackTrace();

}finally{

try{

fWriter.flush();

fWriter.close();

} catch (IOException ex) {

ex.printStackTrace();

}

}

}

}

参考自官网原文。

② Java中如何用I/O流读取一个Word文档的内容

添加spire.doc.jar为依赖,使用下面的代码可以读取word文档内容到txt文档

import com.spire.doc.Document;

import com.spire.doc.FileFormat;

import java.io.IOException;

public class ConvertWordToOtherFormats {

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

//创建Document对象回

Document doc = new Document();

//加载Word文档

doc.loadFromFile("C:\Users\Administrator\Desktop\test.docx");

//将Word保存为TXT格式答

doc.saveToFile("ToTXT.txt",FileFormat.Txt);

}

③ 如何在Excel VBA 中读写word文档 步骤

1.库的配置在默认情况下,新创建的excel vba中不支持定义word对象。所以需要先引入word库,操作步骤如下:1.1 打开excel vba 界面1.2 选中其中的一个Mole1.3 选择菜单, Tools –> References在打开的对话框中选择类似 "Microsoft Word 14.0 Object Library".1.4 点击OK保存配置。2. 打开文档Set wordApplication = CreateObject("Word.Application")wordApplication.Visible = FalseDim hasOpenDoc As BooleanhasOpenDoc = IsOpen(filePath) ' is a self-defined function to check file is opendIf hasOpenDoc = True thenSet wordDoc = GetObject(filePath)End ifIf hasOpenDoc = False ThenSet wordDoc = wordApplication.Documents.Open(filePath)End ifwordDoc.ActiveWith wordApplicationDim aParagraph As Word.ParagraphFor Each aParagraph In wordDoc.Paragraphs' do some thing to every paragraph.Next aParagraphEnd withwordDoc.CloseSet wordDoc = nothing ' 如下这段代码引用某位牛人的,非常感谢他。由于路径丢失,不能给出链接, 抱歉' 如下的找寻方式,能够正确的找出文件是否被打开Function IsOpen(fileName As String) As BooleanIsOpen = FalseDim findFile As IntegerfindFile = FreeFile()On Error GoTo ErrOpenOpen fileName For Binary Lock Read Write As findFileClose findFileExit FunctionErrOpen:If Err.Number <> 70 ThenMsg = "Error # " & Str(Err.Number) & "was generated by " & Err.Source & Chr(13) & Err.DescriptionMsgBox Msg, "Error", Err.HelpFile, Err.HelpContext ElseIsOpen = TrueEnd IfEnd Function

④ java读取带格式word内容

// 表格类型List<XWPFTable> tableList = doc.getTables();for (int i = 0; i < tableList.size(); i++) {System.out.println(i);XWPFTable table = tableList.get(i);System.out.println(table.getText());} 获取表格中内容可以用这个,但是你说的格式是什么意思,每个字的字体之类的吗?

⑤ 怎么使用JAVA,POI读写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;// 创建WordExtractorextractor = 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 s = new ByteArrayInputStream(b); POIFSFileSystem fs = new POIFSFileSystem();DirectoryEntry directory = fs.getRoot(); DocumentEntry de = directory.createDocument("WordDocument", s); FileOutputStream ostream = new FileOutputStream(path); fs.writeFilesystem(ostream); s.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);

⑥ 读取word文档,并将其中的内容按原来的样式输出,望各位大神赐教!!!

packagecom;importstaticorg.junit.Assert.assertEquals;importjava.io.ByteArrayOutputStream;importjava.io.File;importjava.io.FileOutputStream;importjava.io.IOException;importjava.io.InputStream;importjava.util.Enumeration;importjava.util.zip.ZipEntry;importjava.util.zip.ZipException;importjava.util.zip.ZipFile;importjava.util.zip.ZipOutputStream;importjavax.xml.parsers.DocumentBuilderFactory;importjavax.xml.parsers.ParserConfigurationException;importjavax.xml.transform.Transformer;importjavax.xml.transform.;importjavax.xml.transform.TransformerException;importjavax.xml.transform.TransformerFactory;importjavax.xml.transform.dom.DOMSource;importjavax.xml.transform.stream.StreamResult;importorg.junit.Test;importorg.w3c.dom.Document;importorg.w3c.dom.Element;importorg.xml.sax.SAXException;publicclassInputToword{@()throwsIOException,ZipException,SAXException,ParserConfigurationException,TransformerException,{//读取e盘下的hello.docx文档ZipFiledocxFile=newZipFile(newFile("e:\hello.docx"));//解压缩后获得里面和内容相关的xml,word文档是可以解压的,大家可以解压了试试ZipEntrydocumentXML=docxFile.getEntry("word/document.xml");InputStreamdocumentXMLIS=docxFile.getInputStream(documentXML);DocumentBuilderFactorydbf=DocumentBuilderFactory.newInstance();Documentdoc=dbf.newDocumentBuilder().parse(documentXMLIS);//获得文档里相关的节点ElementdocElement=doc.getDocumentElement();assertEquals("w:document",docElement.getTagName());ElementbodyElement=(Element)docElement.getElementsByTagName("w:body").item(0);assertEquals("w:body",bodyElement.getTagName());ElementpElement=(Element)bodyElement.getElementsByTagName("w:p").item(0);assertEquals("w:p",pElement.getTagName());ElementrElement=(Element)pElement.getElementsByTagName("w:r").item(0);assertEquals("w:r",rElement.getTagName());ElementtElement=(Element)rElement.getElementsByTagName("w:t").item(0);assertEquals("w:t",tElement.getTagName());//查找文档中的Hello,fromOffice2007!文字部分assertEquals("Hello,fromOffice2007!",tElement.getTextContent());//写入新的内容tElement.setTextContent("哈哈,终于可以用java写word了,Hello,Office2007,fromJava6!");Transformert=TransformerFactory.newInstance().newTransformer();ByteArrayOutputStreambaos=newByteArrayOutputStream();t.transform(newDOMSource(doc),newStreamResult(baos));//创建新的要输出的word文档,按钮原来word文档的内容写入新的文档中。ZipOutputStreamdocxOutFile=newZipOutputStream(newFileOutputStream("e:\response.docx"));EnumerationentriesIter=docxFile.entries();while(entriesIter.hasMoreElements()){ZipEntryentry=(ZipEntry)entriesIter.nextElement();if(entry.getName().equals("word/document.xml")){byte[]data=baos.toByteArray();docxOutFile.putNextEntry(newZipEntry(entry.getName()));docxOutFile.write(data,0,data.length);docxOutFile.closeEntry();}else{InputStreamincoming=docxFile.getInputStream(entry);byte[]data=newbyte[1024*16];intreadCount=incoming.read(data,0,data.length);docxOutFile.putNextEntry(newZipEntry(entry.getName()));docxOutFile.write(data,0,readCount);docxOutFile.closeEntry();}}docxOutFile.close();}}

⑦ 如何用c++读取word文档

基本步骤(1)创建)一个 MFC 的程序工程。

注意:在VC中对WORD进行操作需要在MFC AppWizard – Step 2 of4中的Automaiton选项上打上勾。

(2)Ctrl+W 执行 ClassWizard(本文按照 VC6 操作,示例程序是在VC6 下编写测试的)。

(3)Add Class…From a type Library… 在 Office目录中,找到想使用的类型库。(我使用的是 Office2003,其Word 的类型库文件,保存在 E:ProgramFilesMicrosoft OfficeOffice12MSWOR.OLB)。

(4)选择类型库文件后,在弹出的对话窗中继续选择要添加的类。具体选择什么类,要看你将来在程序中打算调用什么功能。当然,也可以不用考虑这么多,用鼠标和Shift键配合,全部选择也可以。

(5)初始化COM。方法一,找到App的InitInstance()函数,在其中添加AfxOleInit()函数的调用;方法二,在需要调用COM功能的地方 CoInitialize(NULL),调用完毕后CoUninitialize()。

(6)在你需要调用 Office 功能函数的 cpp 文件中#include<atlbase.h> //为了方便操作 VARIANT 类型变量,使用 CComVariant 模板类#include "文件名.h" //具体的头文件名,是由装载类型库的文件名决定的,如MSWORD。

示例程序:

//word应用程序_Applicationapp;//初始化连接app.CreateDispatch("word.Application");Documentsdoc;CComVarianta(_T(strWord)),b(false),c(0),d(true),aa(0),bb(1);_Documentdoc1;doc.AttachDispatch(app.GetDocuments());doc1.AttachDispatch(doc.Add(&a,&b,&c,&d));Rangerange;//求出文档的所选区域range=doc1.GetContent();//取出文件内容str=range.GetText();m_richedit.SetWindowText(str);//关闭app.Quit(&b,&c,&c);//释放环境app.ReleaseDispatch();

⑧ c#中如何读取word文档,急用!

给你的对文件操作的类吧:public class FileControl { public FileControl() { } /**/ /// /// 在根目录下创建文件夹 /// /// 要创建的文件路径 public void CreateFolder(string FolderPathName) { if (FolderPathName.Trim().Length > 0) { try { string CreatePath = System.Web.HttpContext.Current.Server.MapPath ("../../../Images/" + FolderPathName).ToString(); if (!Directory.Exists(CreatePath)) { Directory.CreateDirectory(CreatePath); } } catch(Exception ex) { throw; } } } /**/ /// /// 删除一个文件夹下面的字文件夹和文件 /// /// public void DeleteChildFolder(string FolderPathName) { if (FolderPathName.Trim().Length > 0) { try { string CreatePath = System.Web.HttpContext.Current.Server.MapPath (FolderPathName).ToString(); if (Directory.Exists(CreatePath)) { Directory.Delete(CreatePath, true); } } catch(Exception ex) { throw; } } } /**/ /// /// 删除一个文件 /// /// public void DeleteFile(string FilePathName) { try { FileInfo DeleFile = new FileInfo(System.Web.HttpContext.Current.Server.MapPath (FilePathName).ToString()); DeleFile.Delete(); } catch(Exception ex) { throw; } } public void CreateFile(string FilePathName) { try { //创建文件夹 //string[] strPath= FilePathName.Split('/'); //CreateFolder(FilePathName.Replace("/" + strPath[strPath.Length-1].ToString(),"")); //创建文件夹 FileInfo CreateFile =new FileInfo(FilePathName); //创建文件 if(!CreateFile.Exists) { FileStream FS=CreateFile.Create(); FS.Close(); } } catch(Exception ex) { throw; } } /**/ /// /// 删除整个文件夹及其字文件夹和文件 /// /// public void DeleParentFolder(string FolderPathName) { try { DirectoryInfo DelFolder = new DirectoryInfo(System.Web.HttpContext.Current.Server.MapPath (FolderPathName).ToString()); if (DelFolder.Exists) { DelFolder.Delete(); } } catch { } } /**/ /// /// 在文件里追加内容 /// /// public void ReWriteReadinnerText(string FilePathName, string WriteWord) { try { //建立文件夹和文件 //CreateFolder(FilePathName); //CreateFile(FilePathName); //得到原来文件的内容 FileStream FileRead = new FileStream(FilePathName, FileMode.Append,FileAccess.Write); //StreamReader FileReadWord = new StreamReader(FileRead, System.Text.Encoding.Default); //string OldString = FileReadWord.ReadToEnd().ToString(); //OldString = OldString + WriteWord; //把新的内容重新写入 StreamWriter FileWrite = new StreamWriter(FileRead, System.Text.Encoding.Default); FileWrite.Write(WriteWord); //关闭 FileWrite.Close(); //FileReadWord.Close(); FileRead.Close(); } catch(Exception ex) { // throw; } } /**/ /// /// 在文件里追加内容 /// /// public string ReaderFileData(string FilePathName) { try { FileStream FileRead = new FileStream(System.Web.HttpContext.Current.Server.MapPath (FilePathName).ToString(), FileMode.Open, FileAccess.Read); StreamReader FileReadWord = new StreamReader(FileRead, System.Text.Encoding.Default); string TxtString = FileReadWord.ReadToEnd().ToString(); //关闭 FileReadWord.Close(); FileRead.Close(); return TxtString; } catch { throw; } } /**/ /// /// 读取文件夹的文件 /// /// /// public DirectoryInfo checkValidSessionPath(string FilePathName) { try { DirectoryInfo MainDir = new DirectoryInfo(System.Web.HttpContext.Current.Server.MapPath (FilePathName)); return MainDir; } catch { throw; } } }我用这个操作文本文件,应该也可以操作WORD文档.另外给个C#操纵WORD文档的例子http://blog.csdn.net/viniboy1982/archive/2006/12/06/1432472.aspx

⑨ 如何在控制台程序中读取WORD文档的内容

1.在VC中新建一控制台程序,选支持MFC(当然,你也可以不选择支持MFC的,不过会很麻烦)2.按CTRL+W调出MFC ClassWizard,Add Class->From a type library,选择你的word的类型库(例如我的是word2003,安装在e盘,我的路径是"e:\edittools\microsoft office\office11\msword.olb"),选择完毕后,在弹出的窗口中选择要让classwizard生成的包装类,在本例中要用到_Application,Documents,_Document,Range这四个类,选中他们后按OK3.进入你的main函数所在的cpp文件,加入头文件引用#include "msword.h" //引用刚才classwizard生成的idispatch包装类4.加入代码int _tmain(int argc, TCHAR* argv[], TCHAR* envp[]){int nRetCode = 0;if (!AfxWinInit(::GetMoleHandle(NULL), NULL, ::GetCommandLine(), 0)){cerr

⑩ 通过文件流读写word文档时乱码怎么解决

有时候打开Word文档可能会看见文档变成了一堆乱码。不用着急,可以试着通过电脑爱好者版提供的两个方权法来挽救你的文件。一、替换格式法就是把损坏的Word文档存为另一种格式。1、打开被损坏的文档单击文件/另存为菜单,在 保存类型列表中,选择RTF格式,然后单击保存按钮,并关闭word。2、打开刚才保存的RTF格式文件,再次使用 另存为将文件重新保存为Word文档,现在打开这个word文件就可以发现文件已经被恢复过来了。如果在转换成rtf格式后文件仍然不能被恢复,可以将文件再次转换为纯文本格式(*.txt),再转换回Word格式。当然在转换为txt文件的时候其图片等信息会丢失掉。二、删除格式信息法Word文档的最后一个段落符号记录着全篇文档的格式信息,有时删除这些格式信息就可以恢复变成乱码的文件。1、在打开损坏的文档后,单击工具/选项菜单,选择编辑标签,取消对使用智能段落选择范围复选框的勾选,然后单击 按钮。这样就可以修复文件了。2、选定最后一个段落符之外的全部内容,然后将这些内容粘贴复制到新的word文件中即可。


赞 (0)