draco1023
6/27/2016 - 12:24 PM

Word replace with netoffice

Word replace with netoffice

public void Test() {
  NetOffice.WordApi.Application app = null;
  NetOffice.WordApi.Document doc = null;

  try
  {
      var tempFile = new FileInfo(path).CopyTo(Path.GetTempFileName(), true);
      app = new NetOffice.WordApi.Application();
      app.Visible = false;
      app.DisplayAlerts = WdAlertLevel.wdAlertsNone;
      app.Options.AutoFormatAsYouTypeReplaceQuotes = false;

      doc = app.Documents.Open(tempFile.FullName);

      var htmlFile = tempFile.FullName + ".html";
      doc.SaveAs(htmlFile, WdSaveFormat.wdFormatFilteredHTML);
      doc.Close();

      doc = app.Documents.Open(tempFile.FullName);
      
      // 查找替换
      
      var find = doc.Content.Find;
      find.ClearFormatting();
      find.Forward = true;
      find.Text = "";
      find.Font.Underline = WdUnderline.wdUnderlineSingle;
      //find.Font.Subscript = 1;
      find.Replacement.ClearFormatting();
      find.Replacement.Text = "<span style=\"text-decoration:underline;\">^&</span>";
      //find.Replacement.Font.Subscript = 0;
      find.Replacement.Font.Underline = WdUnderline.wdUnderlineNone;

      var succ = find.Execute(null, null, null, null, null, null, null, null, null, null, WdReplace.wdReplaceAll);

      find.Font.Underline = WdUnderline.wdUnderlineNone;
      find.Font.Subscript = 1;
      find.Replacement.Text = "<sub>^&</sub>";
      find.Replacement.Font.Subscript = 0;
      succ = find.Execute(null, null, null, null, null, null, null, null, null, null, WdReplace.wdReplaceAll);

      find.Font.Superscript = 1;
      find.Replacement.Text = "<sup>^&</sup>";
      find.Replacement.Font.Superscript = 0;
      succ = find.Execute(null, null, null, null, null, null, null, null, null, null, WdReplace.wdReplaceAll);
      
      find.Text = "\\<span class=\"dot\"\\>(*)\\</span\\>";
      find.Replacement.ClearFormatting();
      find.Replacement.Text = @"\1";
      find.Replacement.Font.EmphasisMark = WdEmphasisMark.wdEmphasisMarkUnderSolidCircle;
      find.Execute(null, null, null, null, null, null, null, null, null, null, WdReplace.wdReplaceAll);
  }
  catch (Exception ex)
  {
  }
  finally
  {
      if (doc != null)
      {
          try
          {
              doc.Close(WdSaveOptions.wdDoNotSaveChanges);
              doc.Dispose();
          }
          catch (Exception)
          {
          }
      }
      if (app != null)
      {
          try
          {
              app.Quit();
              app.Dispose();
          }
          catch (Exception)
          {
          }
      }
  }
}