2012-02-09 4 views
0

C#에서 단어 문서를 자동화 한 후 바탕 화면에 기존 docx 파일을 저장하려고합니다. 내 응용 프로그램을 실행하는 창 양식을 사용하고 있습니다. 바탕 화면에 동일한 파일 이름이 없으면 문서를 저장할 수 있습니다. 그러나 동일한 파일 이름을 다시 저장하려고하면 다음과 같은 오류 메시지가 나타납니다.기존 단어 문서를 저장하는 데 문제가 있습니다.

다른 프로세스에서 파일을 사용하고있는 동안에는 저장할 수 없습니다. 새 이름으로 파일을 저장해보십시오 ( ). (C는 ... \ 바탕 화면 \ TempWord.docx는)

내가 기존 파일 이름이 있다면 다른 이름으로 저장을 사용할 수 해요 Microsoft website에서 읽어 자동으로 우선합니다.

이 프로그램이 실행될 때 다른 단어 문서를 전혀 열지 않았기 때문에 이런 종류의 메시지가 나타나는 이유는 분명하지 않습니다.

이 문제를 해결하는 방법이 너무 명확하지 않습니다. . 내가 잘못

편집했던 곳 내가 너무 확실하지 않다

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Windows.Forms; 
using System.Reflection; 
using Microsoft.Office; 
using Word = Microsoft.Office.Interop.Word; 
using System.Runtime.InteropServices; 


namespace TestWordAutoWithTemplate 
{ 
    public partial class Form1 : Form 
    { 
     public Form1() 
     { 
      InitializeComponent(); 
     } 

     private void butGenerate_Click(object sender, EventArgs e) 
     { 


      //OBJECT OF MISSING "NULL VALUE" 
      Object oMissing = Missing.Value; 

      //OBJECTS OF FALSE AND TRUE 
      Object oTrue = true; 
      Object oFalse = false; 

      //CREATING OBJECTS OF WORD AND DOCUMENT 
      Word.Application oWord = new Word.Application(); 
      Word.Document oWordDoc = new Word.Document(); 

      //SETTING THE VISIBILITY TO TRUE 
      //oWord.Visible = true; 

      //THE LOCATION OF THE TEMPLATE FILE ON THE MACHINE 
      Object oTemplatePath = @"C:\Documents and Settings\YYC\Desktop\TestTemplate.dotx"; 

      //ADDING A NEW DOCUMENT FROM A TEMPLATE 
      oWordDoc = oWord.Documents.Add(ref oTemplatePath, ref oMissing, ref oMissing, ref oMissing); 
      int iTotalFields = 0; 

      foreach (Word.Field myMergeField in oWordDoc.Fields) 
      { 
       iTotalFields++; 
       Word.Range rngFieldCode = myMergeField.Code; 
       String fieldText = rngFieldCode.Text; 

       // ONLY GETTING THE MAILMERGE FIELDS 
       if (fieldText.StartsWith(" MERGEFIELD")) 
       { 
        // THE TEXT COMES IN THE FORMAT OF 
        // MERGEFIELD MyFieldName \\* MERGEFORMAT 
        // THIS HAS TO BE EDITED TO GET ONLY THE FIELDNAME "MyFieldName" 
        Int32 endMerge = fieldText.IndexOf("\\"); 
        Int32 fieldNameLength = fieldText.Length - endMerge; 
        String fieldName = fieldText.Substring(11, endMerge - 11); 

        // GIVES THE FIELDNAMES AS THE USER HAD ENTERED IN .dot FILE 
        fieldName = fieldName.Trim(); 

        // **** FIELD REPLACEMENT IMPLEMENTATION GOES HERE ****// 
        // THE PROGRAMMER CAN HAVE HIS OWN IMPLEMENTATIONS HERE 
        if (fieldName == "Name") 
        { 
         myMergeField.Select(); 
         //Check whether the control text is empty 
         if (txtName.Text == "") 
         { 
          oWord.Selection.TypeText(" "); 
         } 
         else 
         { 
          oWord.Selection.TypeText(txtName.Text); 
         } 
        } 
        if (fieldName == "Address") 
        { 
         myMergeField.Select(); 
         //Check whether the control text is empty 
         if (txtAddress.Text == "") 
         { 
          oWord.Selection.TypeText(" "); 
         } 
         else 
         { 
          oWord.Selection.TypeText(txtAddress.Text); 
         } 
        } 

        if (fieldName == "Age") 
        { 
         myMergeField.Select(); 
         // check whether the control text is empty 
         if (txtAge.Text == "") 
         { 
          oWord.Selection.TypeText(" "); 
         } 
         else 
         { 
          oWord.Selection.TypeText(txtAge.Text); 
         } 
        } 

        if (fieldName == "EAddress") 
        { 
         myMergeField.Select(); 
         // check whether the control text is empty 
         if (txtEmail.Text == "") 
         { 
          oWord.Selection.TypeText(" "); 
         } 
         else 
         { 
          oWord.Selection.TypeText(txtEmail.Text); 
         } 
        } 

        if (fieldName == "Company") 
        { 
         myMergeField.Select(); 
         // Check whether the control text is empty 
         if (txtCompany.Text == "") 
         { 
          oWord.Selection.TypeText(" "); 
         } 
         else 
         { 
          oWord.Selection.TypeText(txtCompany.Text); 
         } 
        } 

        if (fieldName == "TelNo") 
        { 
         myMergeField.Select(); 
         // Check whether the control text is empty 
         if (txtTelephone.Text == "") 
         { 
          oWord.Selection.TypeText(" "); 
         } 
         else 
         { 
          oWord.Selection.TypeText(txtCompany.Text); 
         } 
        } 

        if (fieldName == "ODetails") 
        { 
         myMergeField.Select(); 
         // Check whether the control text is empty 
         if (txtOther.Text == "") 
         { 
          oWord.Selection.TypeText(" "); 
         } 
         else 
         { 
          oWord.Selection.TypeText(txtOther.Text); 
         } 
        } 

       } 
      } 

      oWord.Visible = false; 

      //Marshal.ReleaseComObject(oWordDoc.Fields); 
      //Marshal.ReleaseComObject(oWordDoc); 
      //Marshal.; 


      // If you want your document to be saved as docx 
      Object savePath = @"C:\Documents and Settings\YYC\Desktop\TempWord.doc"; 
      //oWordDoc.Save(); 
      oWordDoc.SaveAs(ref savePath 
       //, 
       //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 
       ); 



      // Close the Word document, but leave the Word application open. 
      // doc has to be cast to type _Document so that it will find the 
      // correct Close method. 
      object doNotSaveChanges = Word.WdSaveOptions.wdDoNotSaveChanges; 
      ((Word._Document)oWordDoc).Close(ref doNotSaveChanges, ref oMissing, ref oMissing); 
      oWordDoc = null; 
      // word has to be case to type _Application so that it will find 
      // the correct Quit method. 
      ((Word._Application)oWord).Quit(ref doNotSaveChanges, ref oMissing, ref oMissing); 
      oWord = null; 
      GC.Collect(); 


     } 
    } 
} 

: 어쩌면 나는 보지 못했다 매우 바보 같은 :(이 내 코드입니다


했다 :

+0

저장 만 시도해 보셨습니까? –

+0

@ 500-InternalServerError 예, 파일 이름으로 저장해야합니다. – yyc2001

+0

오류 메시지는 무엇입니까? 또한 Microsoft.Office.Interop을 통해 ComObject를 처리 할 때 Marshal.ReleaseComObject (oWord)를 사용하여 Dispose해야합니다 (예 : – MethodMan

답변

1

코드의이 줄을 버리고 아래 코드를 생성하고 복사하여 새 코드가 다음과 같이 표시되도록합니다.

private void butGenerate_Click(object sender, EventArgs e) 
{ 
    SaveWordTemp2WordDoc();  
} 

public void SaveWordTemp2WordDoc() 
{ 
    //OBJECT OF MISSING "NULL VALUE" 
    object oMissing = System.Reflection.Missing.Value; 
    //OBJECTS OF FALSE AND TRUE 
    Object oTrue = true; 
    Object oFalse = false; 

    //CREATING OBJECTS OF WORD AND DOCUMENT 
    Word.Application oWord = new Word.Application(); 
    Word.Document oWordDoc = new Word.Document(); 

    //SETTING THE VISIBILITY TO TRUE 
    //oWord.Visible = true; 

    //THE LOCATION OF THE TEMPLATE FILE ON THE MACHINE 
    //Change the path to a path like c:\files\docTemps\ 
    Object oTemplatePath = @"C:\Documents and Settings\YYC\Desktop\TestTemplate.dotx"; 

    //ADDING A NEW DOCUMENT FROM A TEMPLATE 
    oWordDoc = oWord.Documents.Add(ref oTemplatePath, ref oMissing, ref oMissing, ref oMissing); 
    int iTotalFields = 0; 

    foreach (Word.Field myMergeField in oWordDoc.Fields) 
    { 
     iTotalFields++; 
     Word.Range rngFieldCode = myMergeField.Code; 
     String fieldText = rngFieldCode.Text; 

     // ONLY GETTING THE MAILMERGE FIELDS 
     if (fieldText.StartsWith(" MERGEFIELD")) 
     { 
      // THE TEXT COMES IN THE FORMAT OF 
      // MERGEFIELD MyFieldName \\* MERGEFORMAT 
      // THIS HAS TO BE EDITED TO GET ONLY THE FIELDNAME "MyFieldName" 
      Int32 endMerge = fieldText.IndexOf("\\"); 
      Int32 fieldNameLength = fieldText.Length - endMerge; 
      String fieldName = fieldText.Substring(11, endMerge - 11); 

      // GIVES THE FIELDNAMES AS THE USER HAD ENTERED IN .dot FILE 
      fieldName = fieldName.Trim(); 

      // **** FIELD REPLACEMENT IMPLEMENTATION GOES HERE ****// 
      // THE PROGRAMMER CAN HAVE HIS OWN IMPLEMENTATIONS HERE 
      if (fieldName == "Name") 
      { 
       myMergeField.Select(); 
       //Check whether the control text is empty 
       if (txtName.Text == "") 
       { 
        oWord.Selection.TypeText(" "); 
       } 
       else 
       { 
        oWord.Selection.TypeText(txtName.Text); 
       } 
      } 
      if (fieldName == "Address") 
      { 
       myMergeField.Select(); 
       //Check whether the control text is empty 
       if (txtAddress.Text == "") 
       { 
        oWord.Selection.TypeText(" "); 
       } 
       else 
       { 
        oWord.Selection.TypeText(txtAddress.Text); 
       } 
      } 

      if (fieldName == "Age") 
      { 
       myMergeField.Select(); 
       // check whether the control text is empty 
       if (txtAge.Text == "") 
       { 
        oWord.Selection.TypeText(" "); 
       } 
       else 
       { 
        oWord.Selection.TypeText(txtAge.Text); 
       } 
      } 

      if (fieldName == "EAddress") 
      { 
       myMergeField.Select(); 
       // check whether the control text is empty 
       if (txtEmail.Text == "") 
       { 
        oWord.Selection.TypeText(" "); 
       } 
       else 
       { 
        oWord.Selection.TypeText(txtEmail.Text); 
       } 
      } 

      if (fieldName == "Company") 
      { 
       myMergeField.Select(); 
       // Check whether the control text is empty 
       if (txtCompany.Text == "") 
       { 
        oWord.Selection.TypeText(" "); 
       } 
       else 
       { 
        oWord.Selection.TypeText(txtCompany.Text); 
       } 
      } 

      if (fieldName == "TelNo") 
      { 
       myMergeField.Select(); 
       // Check whether the control text is empty 
       if (txtTelephone.Text == "") 
       { 
        oWord.Selection.TypeText(" "); 
       } 
       else 
       { 
        oWord.Selection.TypeText(txtCompany.Text); 
       } 
      } 

      if (fieldName == "ODetails") 
      { 
       myMergeField.Select(); 
       // Check whether the control text is empty 
       if (txtOther.Text == "") 
       { 
        oWord.Selection.TypeText(" "); 
       } 
       else 
       { 
        oWord.Selection.TypeText(txtOther.Text); 
       } 
      } 

     } 
    } 

    oWord.Visible = false; 

    // If you want your document to be saved as docx 
    //Change the file Path here to a path other than your desktop 
    Object savePath = @"C:\Documents and Settings\YYC\Desktop\TempWord.doc"; 
    //oWordDoc.Save(); 
    oWordDoc.SaveAs(ref savePath, 
     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 
     ); 

    // Close the Word document, but leave the Word application open. 
    // doc has to be cast to type _Document so that it will find the 
    // correct Close method. 
    object doNotSaveChanges = Word.WdSaveOptions.wdDoNotSaveChanges; 
    System.Runtime.InteropServices.Marshal.ReleaseComObject(oWordDoc); 
    // word has to be case to type _Application so that it will find 
    // the correct Quit method. 
    ((Word._Application)oWord).Quit(ref doNotSaveChanges, ref oMissing, ref oMissing); 
    System.Runtime.InteropServices.Marshal.ReleaseComObject(oWord); 
} 
+0

코드가 ForEach를 벗어나지 않는 경우 foreach를 for 루프로 리팩토링하고 count MethodMan

+0

Oups .SaveAs 코드에 삽입 한 주석을 잊어 버리는 것을 잊어 버렸습니다. 오류가 .SaveAs – yyc2001

+0

에 표시되는지 확인하기 위해 테스트를 진행했는데 문제가 해결 되었습니까? – MethodMan

관련 문제