65.9K
CodeProject 正在变化。 阅读更多。
Home

将 RTF 转换为 TXT 格式

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.82/5 (18投票s)

2005 年 8 月 13 日

CPOL

2分钟阅读

viewsIcon

264845

downloadIcon

1850

使用 Word 自动化将文件转换为 XML、RTF、TXT、HTML 等格式。

引言

通常需要将文件从一种格式转换为另一种格式。市面上大多数工具似乎都需要付费。虽然价格不贵,但它们并非免费。无论如何,您可能需要转换的几种文件类型都可以通过 Microsoft Word 完成。以下是使用 C# 访问 Word 自动化对象以读取文件类型,然后写入不同文件类型的示例。

背景

我需要将 RFT 格式转换为 TXT。在寻找解决方案时,我很难找到一个免费的。因此,我决定使用 Word 自动化来实现我的目标。请注意,在此示例中我使用的是 Office 2003。如果您没有 Office 2003,这可能仍然有效,除了 XML 输出,因为 XML 是 Word 2003 的新功能。我包含在下载中的示例程序允许您设置一个输入文件。该文件被加载到 Word 对象中。然后有一个 ComboBox 包含一个可以转换为的格式列表。

代码

要进行 Word 自动化,您需要将 Word DLL 的引用添加到您的项目中。

添加项目引用。单击 COM 选项卡。在底部附近,您将找到 Microsoft Word 11.0 对象库。选择并添加到引用。现在您将能够在代码中访问 Word 功能。

private void ConvertFile()
{
  String inFileName = txtBoxInputFile.Text;
  if (!File.Exists(inFileName))
  { //Valid file wasn't entered.
    MessageBox.Show(inFileName + "does not exist." +   
        "Please select an existing file to convert.");
    return;
  }
  // Get the myItem object from the selected 
  // item in the save as combo box.
  myItem tmpItem = 
         cmbBoxOutput.SelectedItem as myItem;

  //Set some vars
  object fileName = inFileName; 
  object fileSaveName = inFileName.Substring(0,
                       inFileName.LastIndexOf("."))  
                       + tmpItem.ItemExtension; //".txt";
  object  vk_read_only  = false;
  object  vk_visible  = true;
  object  vk_true    = true;
  object  vk_false    = false; 
  object  vk_dynamic  = 2;

  object missing = System.Reflection.Missing.Value; 
  // the way to handle parameters you 
  // don't care about in .NET 
  object  vk_range = missing;
  object  vk_to = missing;
  object  vk_from = missing;
  Microsoft.Office.Interop.Word.ApplicationClass vk_word_app = 
           new Microsoft.Office.Interop.Word.ApplicationClass();
            
  // Open the document that was chosen by the dialog 
  Microsoft.Office.Interop.Word.Document aDoc = null;
  try
  {
    aDoc = vk_word_app.Documents.Open(
                 ref fileName, ref missing, 
                 ref vk_read_only, ref missing, 
                 ref missing, ref missing, 
                 ref missing, ref missing, 
                 ref missing, ref missing, 
                 ref missing, ref vk_visible, 
                 ref missing, ref missing, 
                 ref missing, ref missing );                 
  }
  catch (System.Exception ex)
  { 
                
    MessageBox.Show("There was a problem opening "+
                  fileName +" error:"+ex.ToString());
  }

  // Save the doc as the format requested file
  try
  {

  //Get the word saveas format from 
  //the myItem object we got from the 
  //save as combo box selected item
  object vk_saveformat = tmpItem.ItemWord;
            
  aDoc.SaveAs(ref fileSaveName, ref vk_saveformat, 
       ref missing, ref missing, ref missing, ref missing,
       ref missing, ref missing, ref missing, ref missing, 
       ref missing, ref missing, ref missing, ref missing, 
       ref missing, ref missing);
  }
  catch (System.Exception ex)
  { MessageBox.Show("Error : "+ex.ToString());}
  finally
  { //Don't forget to close everything up...
    if (aDoc != null)
    {
      aDoc.Close(ref vk_false, ref missing, ref missing);
    }
    vk_word_app.Quit(ref vk_false,ref missing,ref missing);
  }
}

完成工作的主要内容是 Word SaveFormat。

Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatRTF

WdSaveFormat 下,您拥有 Word 在执行“另存为”时显示的所有可用格式。我将这些格式存储在 ComboBox 中的 myItem 类中。

public class myItem
{
  //vars to hold the property
  private String _itemName; 
  private String _itemExtension;
  private Object _itemWord;

  ...

  //This is the work saveas format object
  public Object ItemWord 
  {
    get{ return _itemWord; }
    set{ _itemWord = value; }
  }

  // This is what causes the combo box 
  // name to show up correctly.
  public override String ToString() 
  {
    return ItemName.ToString ();
  }
  //The constructors
  public myItem(){}

  public myItem(String inName, 
           String inExtension, Object inWordType)
  { // This allows us to set the properties 
    // when the object is created.
    ItemName = inName;
    ItemExtension = inExtension;
    ItemWord = inWordType;
  }
}

加载 ComboBox 的方式如下所示

cmbBoxOutput.Items.Add(new myItem("XML Doc *.xml)", ".xml", 
    Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatXML));

结论

因此,这是一个相当简单的解决方案。重要的是要注意,当您保存为 XML 时,您将获得包含在 XML 中的 Word 格式设置。其中一些可能不是您在 XML 文档中想要的。尽管如此,该解决方案对于将 RTF 格式转换为 TXT 仍然有效。

感谢所有帮助我构建此解决方案的其他 CodeProject 文章。

© . All rights reserved.