簡體   English   中英

C#將datagridview選定的行導出到Word

[英]C# Export datagridview Selected rows 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;

我在DreaminCode上找到了解決方案

被替換的object replace = 2; object replace = 1; 並且它工作完美。

如果您有興趣,可以嘗試我們的第三方GemBox.Document庫,以更輕松的方式獲得所需的效果。 您當前使用的方法存在以下問題:

  1. 使用硬編碼的字符串“ 1”,“ 2”,...作為占位符容易出錯
  2. 如果沒有復雜的模板文件,很難甚至不可能通過搜索和替換導入多行
  3. 由於您的應用程序使用Word Interop,因此只能在安裝了MS Word的計算機上運行。

使用我們的組件,您可以輕松地將所有選定的DataGridView行數據導入到Word文檔中。 這是一個示例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"));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM