C#Interop Word - 从字符串中读取RTF数据

时间:2013-04-15 14:49:18

标签: c# ms-word load interop word-2003

我在字符串str中有RTF数据,我希望将这些数据加载到MS word对象中。我见过Documents.Open()方法但它需要一个物理文件路径来读取特定文件而我没有这样的文件。

如何打开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 个答案:

答案 0 :(得分:1)

我没有尝试将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);