![](/img/trans.png)
[英]How to get text by page from word file (.Docx) using Microsoft.Office.Interop.Word in C#
[英]How to get the range of particular text from a doc file using Word interop and C#
我想創建一個doc文件,並使用word interop和c#將一些內容復制到另一個doc文件中。
這是我的文檔文件。我僅將這部分粘貼到另一個文檔文件中。 其余文本將僅保留在此處。
我只想將文本“僅將這部分粘貼到另一個doc文件。將其余部分粘貼到”另一個DOc文件。 任何人都可以幫助我從我正在使用Interop的文檔中獲取此行的范圍,但要從doc文件中獲取到特定單詞的范圍,而不是選擇該范圍內的文本以將其復制到另一個doc文件中。.我想知道獲得范圍的方法
如果文檔可以是DOCX,則可以使用非常簡單的DOCX包裝器。 合並文檔,更改文本部分,僅查找和替換某些單詞真的非常簡單。 作者在他的Blog網站上編寫了許多很好的使用方法。
但是,如果要DOC,則必須使用Interop。
例如,如果您想查找某個單詞並將其替換為另一個單詞,則可以按照博客上的建議進行操作:
此版本的DocX允許您在文檔中搜索字符串。 函數FindAll(string str)返回一個列表,其中包含找到的字符串的所有起始索引。 以下是此新功能的示例。
// Load a document
using (DocX document = DocX.Load(@"Test.docx"))
{
// Loop through the paragraphs in this document.
foreach (Paragraph p in document.Paragraphs)
{
// Find all instances of 'go' in this paragraph.
List<int> gos = document.FindAll("go");
/*
* Insert 'don't' in front of every instance of 'go' in this document to produce * 'don't go'. An important trick here is to do the inserting in reverse document * order. If you inserted in document order, every insert would shift the index * of the remaining matches.
*/
gos.Reverse();
foreach (int index in gos)
{
p.InsertText(index, "don't ", true);
}
}
// Save all changes made to this document.
document.Save();
}// Release this document from memory.
對於DOC和搜索特定的字符串,也許您可以將整個doc復制到剪貼板並找到所需的內容,然后將其剪切掉:
Word.ApplicationClass wordApp=new ApplicationClass();
object file=path;
object nullobj=System.Reflection.Missing.Value;
Word.Document doc = wordApp.Documents.Open(ref file, ref nullobj, ref nullobj,
ref nullobj, ref nullobj, ref nullobj,
ref nullobj, ref nullobj, ref nullobj,
ref nullobj, ref nullobj, ref nullobj);
doc.ActiveWindow.Selection.WholeStory();
doc.ActiveWindow.Selection.Copy();
IDataObject data=Clipboard.GetDataObject();
txtFileContent.Text=data.GetData(DataFormats.Text).ToString();
doc.Close();
請記住釋放資源,否則最終將打開許多word.exe進程。
這也是一本很好的讀物 ,可以對您有所幫助。
您可能想閱讀幾篇文章:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.