Click here to Skip to main content
15,887,027 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to export the columns I pulled into the datagridview with Checkbox to Word. However, it also exports the hidden columns to Word that I have not checked with the checkboxes and that do not appear in the datagridview. I want to export only selected columns as shown in the image. What is the solution?

What I have tried:

C#
public void Export_Data_To_Word(DataGridView DGV, string filename)
  {
      if (DGV.Rows.Count != 0)
      {
          int RowCount = DGV.Rows.Count;
          int ColumnCount = DGV.Columns.Count;
          Object[,] DataArray = new object[RowCount + 1, ColumnCount + 1];

          //add rows
          int r = 0;
          for (int c = 0; c <= ColumnCount - 1; c++)
          {
              for (r = 0; r <= RowCount - 1; r++)
              {
                  DataArray[r, c] = DGV.Rows[r].Cells[c].Value;
              } //end row loop
          } //end column loop

          Word.Document oDoc = new Word.Document();
          oDoc.Application.Visible = true;

          //page orientation
          oDoc.PageSetup.Orientation = Word.WdOrientation.wdOrientLandscape;

          dynamic oRange = oDoc.Content.Application.Selection.Range;
          string oTemp = "";
          for (r = 0; r <= RowCount - 1; r++)
          {
              for (int c = 0; c <= ColumnCount - 1; c++)
              {
                  oTemp = oTemp + DataArray[r, c] + "\t";

              }
          }

          //table format
          oRange.Text = oTemp;

          object Separator = Word.WdTableFieldSeparator.wdSeparateByTabs;
          object ApplyBorders = true;
          object AutoFit = true;
          object AutoFitBehavior = Word.WdAutoFitBehavior.wdAutoFitContent;

          oRange.ConvertToTable(ref Separator, ref RowCount, 
                                     ref ColumnCount,
                                Type.Missing, Type.Missing, 
                                     ref ApplyBorders,
                                Type.Missing, Type.Missing, Type.Missing,
                                Type.Missing, Type.Missing, Type.Missing,
                                Type.Missing, ref AutoFit, 
                                     ref AutoFitBehavior, Type.Missing);

          oRange.Select();

          oDoc.Application.Selection.Tables[1].Select();
          oDoc.Application.Selection.Tables[1].Rows.AllowBreakAcrossPages = 0;
          oDoc.Application.Selection.Tables[1].Rows.Alignment = 0;
          oDoc.Application.Selection.Tables[1].Rows[1].Select();
          oDoc.Application.Selection.InsertRowsAbove(1);
          oDoc.Application.Selection.Tables[1].Rows[1].Select();

          //header row style
          oDoc.Application.Selection.Tables[1].Rows[1].Range.Bold = 1;
          oDoc.Application.Selection.Tables[1].Rows[1].Range.Font.Name = 
           "Tahoma";
          oDoc.Application.Selection.Tables[1].Rows[1].Range.Font.Size = 14;

          //add header row manually
          for (int c = 0; c <= ColumnCount - 1; c++)
          {
              oDoc.Application.Selection.Tables[1].Cell
                   (1, c + 1).Range.Text = DGV.Columns[c].HeaderText;
          }

          //table style 
          oDoc.Application.Selection.Tables[1].Rows[1].Select();
          oDoc.Application.Selection.Cells.VerticalAlignment = 
              Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;

          //header text
          foreach (Word.Section section in 
                   oDoc.Application.ActiveDocument.Sections)
          {
              Word.Range headerRange =        
      section.Headers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
              headerRange.Fields.Add(headerRange, 
                 Word.WdFieldType.wdFieldPage);
              headerRange.Text = "your header text";
              headerRange.Font.Size = 16;
              headerRange.ParagraphFormat.Alignment = 
                 Word.WdParagraphAlignment.wdAlignParagraphCenter;
          }

          //save the file
          oDoc.SaveAs2(filename);
      }
  }

private void ComboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    using (OleDbConnection conn = new OleDbConnection
          (@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source = 
           siniflisteleri25.accdb; 
           Jet OLEDB:Database Password = Fatih2541; Mode = ReadWrite"))
    {
        string query = "SELECT tcno,ono,isim,soyisim,cinsiyet,sinifi,
        dtarihi,atel,btel from ogrencibilgileri25 where 
        sinifi='" + ComboBox1.Text + " '";

        OleDbCommand command = new OleDbCommand(query, conn);
        conn.Open();
        var adapter = new OleDbDataAdapter(command);
        var table = new System.Data.DataTable();
        adapter.Fill(table);
        dataGridView3.Columns["tcno"].Visible = tcnochk.Checked;
        dataGridView3.Columns["dtarihi"].Visible = dogchk.Checked;
        dataGridView3.Columns["dtarihi"].Visible = dogchk.Checked;
        dataGridView3.Columns["atel"].Visible = atelchk.Checked;
        dataGridView3.Columns["btel"].Visible = btelchk.Checked;
        dataGridView3.DataSource = table;
        conn.Close();
    }
}
Posted
Updated 4-Nov-23 4:54am
v4
Comments
Richard MacCutchan 2-Nov-23 10:17am    
Why are you copying the data into an array and then into the Word document? You can copy direct from your DataGridView.

The problem with your code is setting Visible does not remove the data or columns or rows from the dataset. All of the data is still there, and your code is ignoring which columns and rows have Visible turned off. You're exporting the entire dataset, regardless of any Visible state.
 
Share this answer
 
Comments
Member 12505620 2-Nov-23 13:37pm    
Could you help me to solve the problem please? I am new at c#. I don't know how to solve.
Well... A code inside a Export_Data_To_Word(DataGridView DGV, string filename) should do:

  1. create new Word file
  2. insert new table

    • the number of columns have to be equal to the dgv's columns
    • the number of rows have to be equal to the dgv's visible rows
  3. write the content of each cell into a cell of document table
  4. save the document


Think of it and try to re-write code by yourself. If you get stuck, come back here and show us your progress.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900