2016-11-18 5 views
1

테이블이 포함 된 단어 템플릿 파일이 있으며 11 개의 행과 3 개의 열이 있습니다. 따라서 첫 페이지의 표에는 33 개의 셀이 있습니다. 이 셀에 몇 가지 데이터를 채우지 만 레코드 수가 33보다 큰 경우 66, 두 개의 파일을 만들고 있는데 각각 33 개의 레코드가 들어 있습니다. 나는 66 개의 모든 레코드를 포함 할 단일 파일을 만들고 두 개의 개별 파일 대신 한 파일에 두 페이지가 있어야합니다. 어떻게해야합니까?Word Interop C# : 기존 페이지를 사용하여 새 페이지 삽입

다음은 하나의 doc 파일을 만드는 데 사용하는 코드입니다.

private static string FillTemplate(List<ClientListItem> clients, string fileName) 
    { 
     //Filled document file name 
     var savedFileName = string.Empty; 
     //Search template file in current directory 
     var templateFilePath = System.AppDomain.CurrentDomain.BaseDirectory + "templateFile.doc"; 

     #region Generate file for labels 

     object missing = System.Type.Missing; 
     // Create Word application 
     WORD._Application app = new WORD.Application(); 

     try 
     { 
      Print("Creating label document."); 
      // Create new file 
      WORD._Document doc = app.Documents.Open(templateFilePath); 

      //Print("Creating app selection object"); 
      WORD.Selection selection = app.Selection; 

      //If the template file contains tables 
      if (selection.Tables.Count > 0) 
      { 
       //Use first table 
       //Table's are accessed with starting index as 1 not 0 
       var tableToUse = selection.Tables[1]; 

       //Counter for number of parent caregivers inserted 
       var counter = 0; 
       //Number of parent caregivers 
       var numberOfParentCaregivers = clients.Count; 
       //Loop on each row 
       //Rows are accessed with starting index as 1 not 0 
       for (int rowIndex = 1; rowIndex <= tableToUse.Rows.Count; rowIndex++) 
       { 
        //Loop on each column 
        //Columns are accessed with starting index as 1 not 0 
        for (int columnIndex = 1; columnIndex <= tableToUse.Columns.Count; columnIndex++) 
        { 
         //If counter has reached to its limit 
         if (counter + 1 > numberOfParentCaregivers) 
         { 
          //Stop 
          break; 
         } 

         //If current column index is even 
         if (columnIndex % 2 == 0) 
         { 
          //Do not process it 
          //Why? Check template file for yourself 
          continue; 
         } 

         //Get parent caregiver to set 
         var parentCaregiver = clients[counter]; 

         Print("Generating label to add to document."); 

         //Get label to add to document 
         var labelToAdd = string.Format("{0} {1},{6}{2},{6} {3}, {4} {5}", parentCaregiver.Parent1LastName, parentCaregiver.Parent1FirstName, 
          parentCaregiver.Parent1StreetAddress, parentCaregiver.Parent1City, parentCaregiver.Parent1State, parentCaregiver.Parent1Zip, Environment.NewLine); 

         //Print(string.Format("Adding label {0} at {1}, {2} position.", labelToAdd, rowIndex, columnIndex)); 

         //Get cell to set value 
         var tableCell = tableToUse.Cell(rowIndex, columnIndex); 
         //Set text in cell 
         tableCell.Range.Text = labelToAdd; 
         //Middle align text 
         tableCell.Range.ParagraphFormat.Alignment = WORD.WdParagraphAlignment.wdAlignParagraphCenter; 

         Print(string.Format("Label added {0} at {1}, {2} position.", labelToAdd, rowIndex, columnIndex)); 
         counter++; 
        } 

        //If counter has reched to its limit 
        //i.e. no parent caregivers to process - all processed 
        if (counter + 1 > numberOfParentCaregivers) 
        { 
         //stop 
         break; 
        } 
       } 
      } 

      // Set file name to save 
      savedFileName = string.Format(@"{0}{1}{2}", Path.GetTempPath(), fileName, Path.GetExtension(templateFilePath)); 
      object fname = savedFileName; 
      Print(string.Format("Saving new document at {0}", savedFileName)); 
      // SaveAs new file 
      doc.SaveAs(ref fname, 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, ref missing); 
      Print(string.Format("{0} saved successfully.", savedFileName)); 
      app.Documents.Close(ref missing, ref missing, ref missing); 
     } 
     catch (Exception exc) 
     { 
      Print("Exception while generating label document"); 
      Print(exc.ToString()); 
      //Set file Name to empty string 
      savedFileName = string.Empty; 
     } 
     finally 
     { 
      // Close Word application 
      app.Quit(ref missing, ref missing, ref missing); 
      Marshal.ReleaseComObject(app); 
      app = null; 
      GC.Collect(); 
      GC.WaitForPendingFinalizers(); 
      GC.Collect(); 
      GC.WaitForPendingFinalizers(); 
     } 

     //Return saved file name 
     return savedFileName; 

    } 

템플릿 파일에 추가 할 레코드 수에 따라 원하는만큼 페이지를 만들 수 있도록 변경하십시오.

감사합니다. Nikhil.

+1

문제를보다 잘 설명하도록 제목을 수정하십시오. 이 질문을 찾으려면 무엇을 입력해야합니까? –

+0

감사합니다. 제안대로 업데이트되었습니다. –

+0

그래서 한 묶음의 문서를 만들 수 있습니다 (두 개는 무리입니다).이 문서 묶음을 단일 문서로 병합하거나 병합하려고합니다. 이 키워드로 google을 시도 했습니까? 나는 많은 결과를 얻었습니다. –

답변

3

테이블의 셀을 루핑하는 대신 테이블에 삽입 할 모든 항목에 대해 반복되는 코드가 변경되었습니다. 이 루프 내에서 열과 행의 인덱스가 증가하고 모든 셀이 채워지면 원본 테이블의 복사본이 붙여진 문서 끝 부분에 페이지 나누기가 삽입됩니다. 이 시점에서 두 개의 인덱스가 1로 재설정되고 새 테이블이 사용되는 것으로 설정되며 모든 것이 정상적으로 계속됩니다.

private static string FillTemplate(List<ClientListItem> clients, string fileName) 
    { 
     //Filled document file name 
     var savedFileName = string.Empty; 
     //Search template file in current directory 
     var templateFilePath = System.AppDomain.CurrentDomain.BaseDirectory + "templateFile.doc"; 



     object missing = System.Type.Missing; 
     // Create Word application 
     WORD._Application app = new WORD.Application(); 

     try 
     { 
      app.Visible = true; 
      Print("Creating label document."); 
      // Create new file 
      WORD._Document doc = app.Documents.Open(templateFilePath); 

      //Print("Creating app selection object"); 
      WORD.Selection selection = app.Selection; 

      //If the template file contains tables 
      if (selection.Tables.Count > 0) 
      { 
       //Use first table 
       var tableToUse = selection.Tables[1]; 

       //copy the empty table in the clipboard 
       WORD.Range range = tableToUse.Range; 
       range.Copy(); 

       int rowIndex = 1; 
       int columnIndex = 1; 

       // loop over all the items to insert 
       foreach (ClientListItem parentCaregiver in clients) 
       { 
        // check if all the cells in the current row have been used 
        if (columnIndex > tableToUse.Columns.Count) 
        { 
         // if this is the case increment the row index and restart from the first column 
         columnIndex = 1; 
         rowIndex++; 
         // check if all the rows in the current table have been used 
         if (rowIndex > tableToUse.Columns.Count) 
         { 
          // if this is the case create a new table and restart from the first row 
          rowIndex = 1; 
          // first go to end of document 
          selection.EndKey(WORD.WdUnits.wdStory, WORD.WdMovementType.wdMove); 
          // then add page break 
          object breakType = WORD.WdBreakType.wdPageBreak; 
          selection.InsertBreak(ref breakType); 
          // add a new table (initially with 1 row and one column) at the end of the document 
          // i.e. on the new page 
          WORD.Table tableCopy = doc.Tables.Add(selection.Range, 1, 1, ref missing, ref missing); 
          // paste the original empty table over the new one 
          tableCopy.Range.Paste(); 
          // makes the copied table the one to use 
          tableToUse = tableCopy; 
         } 
        } 
        Print("Generating label to add to document."); 

        //Get label to add to document 
        var labelToAdd = string.Format("{0} {1},{6}{2},{6} {3}, {4} {5}", parentCaregiver.Parent1LastName, parentCaregiver.Parent1FirstName, 
         parentCaregiver.Parent1StreetAddress, parentCaregiver.Parent1City, parentCaregiver.Parent1State, parentCaregiver.Parent1Zip, Environment.NewLine); 

        //Get cell to set value 
        var tableCell = tableToUse.Cell(rowIndex, columnIndex); 
        //Set text in cell 
        tableCell.Range.Text = labelToAdd; 
        //Middle align text 
        tableCell.Range.ParagraphFormat.Alignment = WORD.WdParagraphAlignment.wdAlignParagraphCenter; 

        Print(string.Format("Label added {0} at {1}, {2} position.", labelToAdd, rowIndex, columnIndex)); 

        columnIndex++; 
       } 


      } 

      // Set file name to save 
      savedFileName = fileName; // string.Format(@"{0}{1}{2}", Path.GetTempPath(), fileName, Path.GetExtension(templateFilePath)); 
      object fname = savedFileName; 
      Print(string.Format("Saving new document at {0}", savedFileName)); 
      // SaveAs new file 
      doc.SaveAs(ref fname, 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, ref missing); 
      Print(string.Format("{0} saved successfully.", savedFileName)); 
      app.Documents.Close(ref missing, ref missing, ref missing); 
     } 
     catch (Exception exc) 
     { 
      Print("Exception while generating label document"); 
      Print(exc.ToString()); 
      //Set file Name to empty string 
      savedFileName = string.Empty; 
     } 
     finally 
     { 
      // Close Word application 
      app.Quit(ref missing, ref missing, ref missing); 
      Marshal.ReleaseComObject(app); 
      app = null; 
      GC.Collect(); 
      GC.WaitForPendingFinalizers(); 
      GC.Collect(); 
      GC.WaitForPendingFinalizers(); 
     } 

     //Return saved file name 
     return savedFileName; 

    } 
+0

당신은 PIA를 사용하고 있습니까, 어떻게 WORD._Application'을 얻었습니까? '사용하기'? –

+2

방금 ​​질문의 원래 코드를 수정했습니다. 작동 시키려면 Microsoft Word Object Library에 대한 참조를 추가하고 WORD = Microsoft.Office.Interop.Word; –

+0

예,이 코드는 Word Interop 라이브러리를 사용합니다. –

1

타 방법, 당신이 그것을 여는 대신 Document에 템플릿 파일을 Add 다음 바로 페이지 나누기 후 템플릿 파일을 삽입 Range.InsertFile를 사용할 수 있다는 것입니다 :

코드입니다 표의 마지막 셀에 도달 할 때마다 난 단지 while 루프를 사용하여 현재 흐름을 유지하고 색인 변수를 사용하여 항목을 열거합니다.

private static string FillTemplate(List<ClientListItem> clients, string fileName) 
{ 
    //Filled document file name 
    var savedFileName = string.Empty; 
    //Search template file in current directory 
    var templateFilePath = System.AppDomain.CurrentDomain.BaseDirectory + "templateFile.doc"; 

    //#region Generate file for labels 

    object missing = System.Type.Missing; 
    // Create Word application 
    WORD._Application app = new WORD.Application(); 

    try 
    { 
     Print("Creating label document."); 
     // Create new file 
     //WORD._Document doc = app.Documents.Open(templateFilePath); 
     // Instead of creating a new file, just add our template to the document 
     WORD._Document doc = app.Documents.Add(templateFilePath); 

     //Print("Creating app selection object"); 
     WORD.Selection selection = app.Selection; 

     //If the template file contains tables 
     if (selection.Tables.Count > 0) 
     { 
      //Use first table 
      //Table's are accessed with starting index as 1 not 0 
      var tableToUse = selection.Tables[selection.Tables.Count]; 

      //Counter for number of parent caregivers inserted 
      var counter = 0; 
      //Number of parent caregivers 
      var numberOfParentCaregivers = clients.Count; 
      //Loop on each row 

      int rowIndex = 1, columnIndex = 1; 

      while (counter < numberOfParentCaregivers) 
      { 
       if(columnIndex > tableToUse.Columns.Count) 
       { 
        // Reset column index if we have reached the last column 
        columnIndex = 1; 
        // And go to the next row 
        rowIndex++; 

        if(rowIndex > tableToUse.Rows.Count) 
        { 
         // Reset row index if we have reached the last row 
         rowIndex = 1; 
         // Go the the end of the document, add a page break and insert our empty table template 
         object startPoint = 0; 
         WORD.Range range = doc.Range(ref startPoint, ref missing); 
         range.Collapse(WORD.WdCollapseDir‌​ection.wdCollapseEnd‌​); 
         range.InsertBreak(WORD.WdBreakTyp‌​e.wdSectionBreakNext‌​Page); 
         range.InsertFile(templateFilePath); 
         // Assign the new inserted template table to our current table to use 
         tableToUse = range.Tables[selection.Tables.Count]; 
        } 
       } 

       var parentCaregiver = clients[counter]; 

       Print("Generating label to add to document."); 

       //Get label to add to document 
       var labelToAdd = string.Format("{0} {1},{6}{2},{6} {3}, {4} {5}", parentCaregiver.Parent1LastName, parentCaregiver.Parent1FirstName, 
        parentCaregiver.Parent1StreetAddress, parentCaregiver.Parent1City, parentCaregiver.Parent1State, parentCaregiver.Parent1Zip, Environment.NewLine); 

       //Print(string.Format("Adding label {0} at {1}, {2} position.", labelToAdd, rowIndex, columnIndex)); 

       //Get cell to set value 
       var tableCell = tableToUse.Cell(rowIndex, columnIndex); 
       //Set text in cell 
       tableCell.Range.Text = labelToAdd; 
       //Middle align text 
       tableCell.Range.ParagraphFormat.Alignment = WORD.WdParagraphAlignment.wdAlignParagraphCenter; 

       Print(string.Format("Label added {0} at {1}, {2} position.", labelToAdd, rowIndex, columnIndex)); 
       // Increate items counter and columns counter on each loop 
       counter++; 
       columnIndex++; 
      } 
     } 

     // Set file name to save 
     savedFileName = string.Format(@"{0}{1}{2}", Path.GetTempPath(), fileName, Path.GetExtension(templateFilePath)); 
     object fname = savedFileName; 
     Print(string.Format("Saving new document at {0}", savedFileName)); 
     // SaveAs new file 
     doc.SaveAs(ref fname, 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, ref missing); 
     Print(string.Format("{0} saved successfully.", savedFileName)); 
     app.Documents.Close(ref missing, ref missing, ref missing); 
    } 
    catch (Exception exc) 
    { 
     Print("Exception while generating label document"); 
     Print(exc.ToString()); 
     //Set file Name to empty string 
     savedFileName = string.Empty; 
    } 
    finally 
    { 
     // Close Word application 
     app.Quit(ref missing, ref missing, ref missing); 
     Marshal.ReleaseComObject(app); 
     app = null; 
     GC.Collect(); 
     GC.WaitForPendingFinalizers(); 
     GC.Collect(); 
     GC.WaitForPendingFinalizers(); 
    } 

    //Return saved file name 
    return savedFileName; 
}