0

文字列に RTF データがあり、strそのデータを 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 }";

Wordでフォーマットを行いますが、applicationClassは次のようにする必要がありますwordapp.Visible = false;

更新:ファイルをシステムに保存したくありません。物理メモリに保存せずに読んで作業する方法はありませんか?

4

1 に答える 1

1

RTF テキストを Word に読み込もうとする代わりに、テキスト ファイルに読み込んで (RTF ファイルはプレーン テキストであるため)、その生の RTF テキスト ファイルを新しい Word 文書として開く方がよいと思います。これにより、Word は RTF テキストを処理し、(フォント/マージン/などを使用して) Word doc としてフォーマットします。これは、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);
于 2013-04-15T18:12:04.000 に答える