2013-05-07 5 views
1

내 양식에 DataGridView이 있습니다. 내가 뭘하려고하면 사용자가 행을 선택하고 해당 행에서 Button(button_1) 데이터를 누르면 단어 문서를 보내고 column[i]에 따라 숫자를 바꿔야합니다. 이제 코드를 사용하여
문제 1 하나의 행을 선택하고 버튼을 클릭하면 데이터가 Word 파일의 번호를 찾은 다음 바꿉니다. 그러나 예를 들어 "1"과 같은 모든 항목을 바꿉니다. 내가 각 행에 대해 그것을하고 싶어하기 때문에 한 번했다. 문제 2 사용자가 둘 이상의 행을 선택한 경우 마지막으로 선택된 행 데이터 만 내보내집니다. 어떤 아이디어 ??C# 데이터 행을 Word로 내보내기

private void button1_Click(object sender, EventArgs e) 
    { 

     string SendPath = ""; 

     if (openFileDialogWord.ShowDialog(this) == DialogResult.OK) 
     { 
      SendPath = (openFileDialogWord.InitialDirectory + openFileDialogWord.FileName).ToString(); 
     } 


     WordDoc(SendPath); 
    } 



    public void WordDoc(string getfilename) 
    { 



     object FileName = getfilename; //The filepath goes here 


     //Create word Application Object 
     Word.Application word = new Word.Application(); 

     //Create word document Object 
     Word.Document doc = null; 

     //Create word Missing Object 
     object missing = System.Type.Missing; 

     object readOnly = false; 
     object isVisible = false; 
     // make visible Word application 
     word.Visible = true; 

     try 
     { 
      doc = word.Documents.Open(ref FileName, 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); 
      doc.Activate(); 




      string Column1; 
      string Column2; 

      foreach (DataGridViewRow rows in dataGridView1.SelectedRows) 
      { 


       Column1 = rows.Cells[1].Value.ToString(); 
       Column2 = rows.Cells[2].Value.ToString(); 

       this.FindAndReplace(word, "1", Column1); 
       this.FindAndReplace(word, "2", Column2); 

      } 

      MessageBox.Show("Complete"); 


     } 
     catch (Exception ex) 
     { 
      MessageBox.Show("Error : " + ex.Message); 
     } 
    } 



    private void FindAndReplace(Word.Application word, object findText, object replaceText) 
    { 
     object matchCase = true; 
     object matchWholeWord = true; 
     object matchWildCards = false; 
     object matchSoundsLike = false; 
     object matchAllWordForms = false; 
     object forward = true; 
     object format = false; 
     object matchKashida = false; 
     object matchDiacritics = false; 
     object matchAlefHamza = false; 
     object matchControl = false; 
     object read_only = false; 
     object visible = true; 
     object replace = 2; 
     object wrap = 1; 
     word.Selection.Find.Execute(ref findText, ref matchCase, 
     ref matchWholeWord, ref matchWildCards, ref matchSoundsLike, 
     ref matchAllWordForms, ref forward, ref wrap, ref format, 
     ref replaceText, ref replace, ref matchKashida, 
     ref matchDiacritics, 
     ref matchAlefHamza, ref matchControl); 
    } 
+0

누군가가 ???????? – user2345661

+0

이 부분에 문제가 있습니다. object replace = 2; DreaminCode에서 해결책을 찾았습니다. 대체 된 개체 replace = 2; 오브젝트 대체 = 1; 그리고 그것은 완벽하게 일하고 있습니다. – user2345661

답변

1

문제가

객체 = 2를 대체 부품이 함께 있었다;

나는 object replace = 1;로 대체 DreaminCode

object replace = 2;에서 해결책을 발견하고는 완벽하게 작동한다.

1

관심있는 분들은 제 3 자 GemBox.Document 라이브러리를 사용해보다 쉬운 방법으로 필요한 효과를 얻을 수 있습니다. 현재의 접근 방식 문제는 다음과 같습니다

  1. 하드 코딩 된 문자열을 사용하여 "1", "2", ... 자리로하는 것은 오류가 발생하기 쉬운입니다
  2. 는 검색과 여러 행을 가져올 하드 또는 불가능 & 복잡한 템플릿 파일없이 바꾸기
  3. Word Interop을 사용하므로 MS Word가 설치된 컴퓨터에서만 응용 프로그램을 실행할 수 있습니다.

이 구성 요소를 사용하면 선택한 모든 DataGridView 행을 Word 문서로 쉽게 가져올 수 있습니다. 다음은 mail merge 사용하여 수행하는 방법 샘플 C# 코드입니다 :

 // Create data source for DataGridView. 
     var people = new DataTable() 
     { 
      Columns = 
      { 
       new DataColumn("Name", typeof(string)), 
       new DataColumn("Surname", typeof(string)) 
      }, 
      Rows = 
      { 
       { "John", "Doe" }, 
       { "Fred", "Nurk" }, 
       { "Hans", "Meier" }, 
       { "Ivan", "Horvat" } 
      } 
     }; 

     // Create DataGridView and show it to select rows. 
     var dataGridView = new DataGridView() 
     { 
      DataSource = people, 
      Dock = DockStyle.Fill 
     }; 
     new Form() { Controls = { dataGridView } }.ShowDialog(); 

     // Get selected items which will be used as data source for mail merge. 
     var selectedItems = dataGridView.SelectedRows.Cast<DataGridViewRow>().Select(dgvRow => dgvRow.DataBoundItem).ToArray(); 

     // Create template document which is usually created with MS Word application and loaded with GemBox.Document library. 
     // This code just shows the structure of the template document. 
     var doc = new DocumentModel(); 
     doc.Sections.Add(
      new Section(doc, 
       new Table(doc, 
        new TableRow(doc, 
         new TableCell(doc, 
          new Paragraph(doc, 
           new Run(doc, "Name") { CharacterFormat = { Bold = true } })), 
         new TableCell(doc, 
          new Paragraph(doc, 
           new Run(doc, "Surname") { CharacterFormat = { Bold = true } }))) 
        { 
         RowFormat = { RepeatOnEachPage = true } 
        }, 
        new TableRow(doc, 
         new TableCell(doc, 
          new Paragraph(doc, 
           new Field(doc, FieldType.MergeField, "RangeStart:SelectedPeople"), 
           new Field(doc, FieldType.MergeField, "Name"))), 
         new TableCell(doc, 
          new Paragraph(doc, 
           new Field(doc, FieldType.MergeField, "Surname"), 
           new Field(doc, FieldType.MergeField, "RangeEnd:SelectedPeople"))))) 
       { 
        TableFormat = { PreferredWidth = new TableWidth(100, TableWidthUnit.Percentage) } 
       })); 

     // Execute mail merge. All selected people will be imported into the document. 
     doc.MailMerge.Execute(selectedItems, "SelectedPeople"); 

     // Save document in DOCX and PDF formats. 
     doc.Save(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "SelectedPeople.docx")); 
     doc.Save(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "SelectedPeople.pdf"));