2013-04-15 57 views
0

我有一個字符串str的RTF數據,我希望數據能夠加載到MS字對象中。我見過Documents.Open()方法,但它需要一個物理文件路徑來讀取一個特定的文件,我沒有這樣的文件。C#Interop Word - 從一個字符串讀取RTF數據

如何打開Word的新實例並在其中加載我的RTF數據?

Microsoft.Office.Interop.Word.ApplicationClass wordapp = new ApplicationClass(); 
wordapp.Visible = false; 

string str = @"{\rtf1\ansi\ansicpg1252\uc1\deff0{\fonttbl{\f0\fnil\fcharset0\fprq2 Arial;}{\f1\fswiss\fcharset0\fprq2 Arial;}{\f2\froman\fcharset2\fprq2 Symbol;}} 
{\colortbl;}{\stylesheet{\s0\itap0\nowidctlpar\f0\fs24 [Normal];}{\*\cs10\additive Default Paragraph Font;}}{\*\generator TX_RTF32 17.0.540.502;} 
\paperw12240\paperh15840\margl1138\margt1138\margr1138\margb1138\deftab1134\widowctrl\formshade\sectd\headery720\footery720\pgwsxn12240\pghsxn15840\marglsxn1138\margtsxn1138\margrsxn1138\margbsxn1138\pgbrdropt32\pard\itap0\nowidctlpar\plain\f1\fs20 test1\par }"; 

我會做一些格式的字,但applicationClass應該wordapp.Visible = false;

更新:我不喜歡被保存在系統中的文件。無論如何讀取和工作,而不將其保存在物理內存上?

+1

如果我得到你的觀點正確,你想要做的RTF數據的格式化沒有物理文件。你可以檢查RichTextBox控件的這個 –

+0

@faheemkhan:那麼這是一個好的開始。我可以閱讀richtextbox中的str。現在我要嘗試將它加載到word doc的新實例中。 –

回答

0

而不是嘗試將RTF文本加載到Word中,我認爲最好將其加載到文本文件中(因爲RTF文件無論如何都是純文本),然後將該原始RTF文本文件作爲新的Word文檔打開。這導致Word處理RTF文本並將其格式化爲Word文檔(包含字體/邊距/等),我認爲這是您要查找的內容,而不是逐字查看RTF文本。一旦它的一個新的Word文檔,你可以做你的操作,然後保存爲Word文檔文件:

 string filePath = @"c:\rawRtfText.rtf"; 

     //write the raw RTF string to a text file. 
     System.IO.StreamWriter rawTextFile = new System.IO.StreamWriter(filePath, false); 
     string str = @"{\rtf1\ansi\ansicpg1252\uc1\deff0{\fonttbl{\f0\fnil\fcharset0\fprq2 Arial;}{\f1\fswiss\fcharset0\fprq2 Arial;}{\f2\froman\fcharset2\fprq2 Symbol;}}{\colortbl;}{\stylesheet{\s0\itap0\nowidctlpar\f0\fs24 [Normal];}{\*\cs10\additive Default Paragraph Font;}}{\*\generator TX_RTF32 17.0.540.502;}\paperw12240\paperh15840\margl1138\margt1138\margr1138\margb1138\deftab1134\widowctrl\formshade\sectd\headery720\footery720\pgwsxn12240\pghsxn15840\marglsxn1138\margtsxn1138\margrsxn1138\margbsxn1138\pgbrdropt32\pard\itap0\nowidctlpar\plain\f1\fs20 test1\par }"; 
     rawTextFile.Write(str); 
     rawTextFile.Close(); 

     //now open the RTF file using word. 
     Microsoft.Office.Interop.Word.Application msWord = new Microsoft.Office.Interop.Word.Application(); 
     msWord.Visible = false; 
     Microsoft.Office.Interop.Word.Document wordDoc = msWord.Documents.Open(filePath); 

     //after manipulating the word doc, save it as a word doc. 
     object oMissing = System.Reflection.Missing.Value; 
     wordDoc.SaveAs(@"c:\RtfConvertedToWord.doc", ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing); 
+0

我不想保存或讀取任何文檔。 –

+0

您的目標是執行打印或將其展示給用戶,然後在不保存的情況下關閉它?或者以更容易的方式操作RTF的格式,然後最終檢索表示該格式的RTF數據?也就是說,要使用Word作爲接口來設置字體/格式/等等,來編寫RTF,以便您不必親自操作RTF? –