从字符串中读取RTF数据
本文关键字:RTF 数据 读取 字符串 | 更新日期: 2023-09-27 18:09:10
我在字符串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 }";
我将在word中做一些格式化,但是applicationClass应该是wordapp.Visible = false;
UPDATE:我不希望文件保存在系统上。如果不把它保存在物理内存中,难道就没有办法读取和工作了吗?
与其尝试将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);