2012-12-20 15 views
9

Sto leggendo il testo dal file word e sostituisco del testo dal testo letto.Copia il testo da file word a una nuova parola

var wordApp = new Microsoft.Office.Interop.Word.Application(); 
object file = path; 

object nullobj = System.Reflection.Missing.Value; 

var doc = wordApp.Documents.Open(ref file, ref nullobj, ref nullobj, 
               ref nullobj, ref nullobj, ref nullobj, 
               ref nullobj, ref nullobj, ref nullobj, 
               ref nullobj, ref nullobj, ref nullobj); 
doc.ActiveWindow.Selection.WholeStory(); 

doc.ActiveWindow.Selection.Copy(); 

IDataObject data = Clipboard.GetDataObject(); 
var text =data.GetData(DataFormats.Text); 

così ho testo da file di Word originale, e ora ho bisogno di passare ad un nuovo file parola che non esiste (nuovo testo).

ho cercato

ProcessStartInfo startInfo = new ProcessStartInfo(); 
startInfo.FileName = "WINWORD.EXE"; 
Process.Start(startInfo); 

Questo apre un nuovo file di Word che non salvato fisicamente nel file di sistema che va bene. Ma non sono sicuro di come possa passare il valore del testo a questo nuovo file.

Aggiornamento

Dopo l'esecuzione di codice sopra ho cercato

var wordApp = new Microsoft.Office.Interop.Word.Application();    
var doc = wordApp.ActiveDocument; 

che esce con "Questo comando non è disponibile perché nessun documento è aperto."

+0

hai visto questo: http: // StackOverflow. it/questions/5160964/copying-contents-of-word-doc-and-paste-into-another-c-sharp – MUG4N

+0

@ MUG4N: Ho visto qualcosa di simile [qui] (http://pastebin.com/1sV8es7b), ma non sono sicuro di cosa sia 'worddocpromo'. Non c'è nessuna spiegazione –

+0

@huMptyduMpty dovresti fare affidamento su word interop per fare questa cosa invece di process.start. Crea un nuovo documento word, imposta il contenuto, salvalo in un'altra posizione, ora aprilo da lì usando process.start o così. Non dimenticare di disporre correttamente gli oggetti COM – nawfal

risposta

4

Ecco un semplice esempio che copia l'intero testo e la formattazione da un documento di Word in un nuovo documento. Nel nuovo documento, il testo viene poi sostituito con le parole Trova & Sostituire caratteristica:

using System; 
using System.Linq; 
using Word = Microsoft.Office.Interop.Word; 

namespace WordCopy 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      var fileName = args[0]; 

      var wordApp = new Word.Application(); 
      wordApp.Visible = true; 
      var document = wordApp.Documents.Open(fileName); 

      var newDocument = CopyToNewDocument(document); 

      SearchAndReplaceEverywhere(newDocument, "this", "that"); 
     } 

     static Word.Document CopyToNewDocument(Word.Document document) 
     { 
      document.StoryRanges[Word.WdStoryType.wdMainTextStory].Copy(); 

      var newDocument = document.Application.Documents.Add(); 
      newDocument.StoryRanges[Word.WdStoryType.wdMainTextStory].Paste(); 
      return newDocument; 
     } 

     static void SearchAndReplaceEverywhere(
      Word.Document document, string find, string replace) 
     { 
      foreach (Word.Range storyRange in document.StoryRanges) 
      { 
       var range = storyRange; 
       while (range != null) 
       { 
        SearchAndReplaceInStoryRange(range, find, replace); 

        if (range.ShapeRange.Count > 0) 
        { 
         foreach (Word.Shape shape in range.ShapeRange) 
         { 
          if (shape.TextFrame.HasText != 0) 
          { 
           SearchAndReplaceInStoryRange(
            shape.TextFrame.TextRange, find, replace); 
          } 
         }       
        } 
        range = range.NextStoryRange; 
       } 
      } 
     } 

     static void SearchAndReplaceInStoryRange(
      Word.Range range, string find, string replace) 
     { 
      range.Find.ClearFormatting(); 
      range.Find.Replacement.ClearFormatting(); 
      range.Find.Text = find; 
      range.Find.Replacement.Text = replace; 
      range.Find.Wrap = Word.WdFindWrap.wdFindContinue; 
      range.Find.Execute(Replace: Word.WdReplace.wdReplaceAll); 
     } 
    } 
} 
4

Tutto quello che dovete fare è questo:

using System.Runtime.InteropServices; 
using MSWord = Microsoft.Office.Interop.Word; 

namespace ConsoleApplication6 
{ 
    class Program 
    { 
     static void Main() 
     { 
      var application = new MSWord.Application(); 
      var originalDocument = application.Documents.Open(@"C:\whatever.docx"); 

      originalDocument.ActiveWindow.Selection.WholeStory(); 
      var originalText = originalDocument.ActiveWindow.Selection; 

      var newDocument = new MSWord.Document(); 
      newDocument.Range().Text = originalText.Text; 
      newDocument.SaveAs(@"C:\whateverelse.docx"); 

      originalDocument.Close(false); 
      newDocument.Close(); 

      application.Quit(); 

      Marshal.ReleaseComObject(application); 
     } 
    } 
} 
Problemi correlati