How to export dataGridView data Instantly to Excel on button click?

前端 未结 14 2229
执笔经年
执笔经年 2020-11-28 05:21

I have 10k rows and 15 column in my data grid view. I want to export this data to an excel sheet o button click. I have already tried with the below code.

pr         


        
14条回答
  •  鱼传尺愫
    2020-11-28 05:36

    This line works only for the DataGridView Control on Windows Forms:

    DataObject dataObj = dataGridView1.GetClipboardContent();
    

    This one addresses the same issue, but for the DataGrid control for the WPF Framework:

        private void copyDataGridContentToClipboard()
        {
            datagridGrupeProductie.SelectAll();
            datagridGrupeProductie.ClipboardCopyMode = DataGridClipboardCopyMode.IncludeHeader;
    
            ApplicationCommands.Copy.Execute(null, datagridGrupeProductie);
            datagridGrupeProductie.UnselectAll();
        }
    
    
        private void rightClickGrupeProductie_Click(object sender, RoutedEventArgs e)
        {
            copyDataGridContentToClipboard();
            Microsoft.Office.Interop.Excel.Application excelApp;
            Microsoft.Office.Interop.Excel.Workbook excelWkbk;
            Microsoft.Office.Interop.Excel.Worksheet excelWksht;
            object misValue = System.Reflection.Missing.Value;
            excelApp = new Microsoft.Office.Interop.Excel.Application();
            excelApp.Visible = true;
            excelWkbk = excelApp.Workbooks.Add(misValue);
            excelWksht = (Microsoft.Office.Interop.Excel.Worksheet)excelWkbk.Worksheets.get_Item(1);
            Microsoft.Office.Interop.Excel.Range CR = (Microsoft.Office.Interop.Excel.Range)excelWksht.Cells[1, 1];
            CR.Select();
            excelWksht.PasteSpecial(CR, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, true);
        }
    

提交回复
热议问题