Mehmet Fatih

Mehmet Fatih

  • 828
  • 930
  • 37.8k

Preventing empty columns when exporting to word document

Nov 5 2023 5:33 AM

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?

 public void Export_Data_To_Word(DataGridView DGV, string filename)
 {
     if (File.Exists(filename))
     {
         File.Delete(filename);
     }
     Object oMissing = System.Reflection.Missing.Value;
     Object oTrue = true;
     Object oFalse = false;
     Word.Application oWord = new Word.Application();
     Word.Document oWordDoc = new Word.Document();
     oWord.Visible = true;
     oWord.WindowState = Word.WdWindowState.wdWindowStateMinimize;
     oWord.WindowState = Word.WdWindowState.wdWindowStateMaximize;


     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++)
         {
             if (DGV.Columns[c].Visible) // Check if the column is visible
             {
                 for (r = 0; r <= RowCount - 1; r++)
                 {

                     DataArray[r, c] = DGV.Rows[r].Cells[c].Value;
                 } //end row loop

             } //end column loop               
         }
      

         //page orintation
         oWordDoc.PageSetup.Orientation = Word.WdOrientation.wdOrientLandscape;


         dynamic oRange = oWordDoc.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();

         oWord.Application.Selection.Borders.InsideLineStyle = Word.WdLineStyle.wdLineStyleSingle; //tablo çizgisi
         oWord.Application.Selection.Borders.OutsideLineStyle = Word.WdLineStyle.wdLineStyleSingle; // tablo çizgisi

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

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

         //add header row manually
         for (int c = 0; c <= DGV.Columns.Count - 1; c++)
         {
             if (DGV.Columns[c].Visible) // Check if the column is visible
             {
                 oWord.Application.Selection.Tables[1].Cell(1, c + 1).Range.Text = DGV.Columns[c].HeaderText;
             }
         }

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

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

         //save the file
         oWord.ActiveDocument.SaveAs2(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Ögrenci Bilgileri.docx"));
         oWordDoc.Close(ref oFalse, ref oMissing, ref oMissing);
         oWord.Quit();
         System.Runtime.InteropServices.Marshal.ReleaseComObject(oWordDoc);
         System.Runtime.InteropServices.Marshal.ReleaseComObject(oWord);
         oWordDoc = null;
         oWord = null;
         GC.WaitForPendingFinalizers();
         GC.Collect();
         MessageBox.Show("Your file is saved");
        

     }
 }

 private void WordeAktar_Load(object sender, EventArgs e)
 {
     SinifCek();
     ComboBox1.SelectedIndex = 0;

     DGV.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
     DGV.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;

     DGV.Columns["tcno"].Visible = tcnochk.Checked; // ilk açilista hangi sütunlari getirecegiyle ilgili
     DGV.Columns["dtarihi"].Visible = dogchk.Checked;
     DGV.Columns["atel"].Visible = atelchk.Checked;
     DGV.Columns["btel"].Visible = btelchk.Checked;


     DGV.TopLeftHeaderCell.Value = "S.No";
     DGV.Columns[0].HeaderText = "T.C.No";
     DGV.Columns[1].HeaderText = "Ö.No";
     DGV.Columns[2].HeaderText = "Adi";
     DGV.Columns[3].HeaderText = "Soyadi";
     DGV.Columns[4].HeaderText = "Cinsiyeti";
     DGV.Columns[5].HeaderText = "Sinifi";
     DGV.Columns[7].HeaderText = "Anne Tel";
     DGV.Columns[8].HeaderText = "Baba Tel";
 }

 private void button1_Click(object sender, EventArgs e)
 {
     SaveFileDialog sfd = new SaveFileDialog();

     sfd.Filter = "Word Documents (*.docx)|*.docx";

     sfd.FileName = "Ögrenci Bilgileri.docx";

     if (sfd.ShowDialog() == DialogResult.OK)
     {

         Export_Data_To_Word(DGV, sfd.FileName);
     }
 }


Answers (11)