C#导出datagridview选定的行到Word

时间:2013-05-07 13:02:10

标签: c# datagridview ms-word export-to-word

我的表格中有DataGridView。我想要做的是,如果用户选择一行并按Button(button_1)该行的数据应该发送到word文档并根据column[i]替换一个数字。 现在使用下面的代码
问题1 当我选择一行并单击按钮时,数据会查找并替换Word文件中的数字,但它会替换所有出现的例如“1”但我只希望它完成一次,因为我想为每一行做这件事。 问题2 如果用户选择多行,则仅导出最后选择的行数据。有任何想法吗??

    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);
    }

2 个答案:

答案 0 :(得分:1)

问题出在本部分

object replace = 2;

我在DreaminCode

找到了解决方案

object replace = 2;替换为object replace = 1;,它正常运作。

答案 1 :(得分:1)

如果您有兴趣,可以尝试我们的第三方GemBox.Document库以更轻松的方式获得所需的效果。 您当前的方法存在以下问题:

  1. 使用硬编码字符串“1”,“2”,...作为占位符容易出错
  2. 使用搜索和输入导入多行很难甚至不可能没有复杂的模板文件替换
  3. 您的应用程序只能在安装了MS Word的计算机上运行,​​因为它使用Word Interop。
  4. 使用我们的组件,您可以轻松地将所有选定DataGridView行的数据导入到Word文档。 下面是一个示例C#代码,如何使用mail merge

    执行此操作
            // 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"));