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

前端 未结 14 2133
执笔经年
执笔经年 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:32

    This is a great question and I was surprised at how difficult it was to find a clear and complete answer, most of the answers I found were either sudo-code or not 100% complete.

    I was able to create a complete solution to copy and save the data from my DataGridView to an excel file based on Jake's answer so I'm posting my complete solution in the hopes that it can help other new comers to c# like myself :)

    First off, you will need the Microsoft.Office.Interop.Excel reference in your project. See MSDN on how to add it.

    My Code:

    using Excel = Microsoft.Office.Interop.Excel;
    
    private void btnExportToExcel_Click(object sender, EventArgs e)
    {
        SaveFileDialog sfd = new SaveFileDialog();
        sfd.Filter = "Excel Documents (*.xls)|*.xls";
        sfd.FileName = "Inventory_Adjustment_Export.xls";
        if (sfd.ShowDialog() == DialogResult.OK)
        {
            // Copy DataGridView results to clipboard
            copyAlltoClipboard();
    
            object misValue = System.Reflection.Missing.Value;
            Excel.Application xlexcel = new Excel.Application();
    
            xlexcel.DisplayAlerts = false; // Without this you will get two confirm overwrite prompts
            Excel.Workbook xlWorkBook = xlexcel.Workbooks.Add(misValue);
            Excel.Worksheet xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
    
            // Format column D as text before pasting results, this was required for my data
            Excel.Range rng = xlWorkSheet.get_Range("D:D").Cells;
            rng.NumberFormat = "@";
    
            // Paste clipboard results to worksheet range
            Excel.Range CR = (Excel.Range)xlWorkSheet.Cells[1, 1];
            CR.Select();
            xlWorkSheet.PasteSpecial(CR, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, true);
    
            // For some reason column A is always blank in the worksheet. ¯\_(ツ)_/¯
            // Delete blank column A and select cell A1
            Excel.Range delRng = xlWorkSheet.get_Range("A:A").Cells;
            delRng.Delete(Type.Missing);
            xlWorkSheet.get_Range("A1").Select();
    
            // Save the excel file under the captured location from the SaveFileDialog
            xlWorkBook.SaveAs(sfd.FileName, Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
            xlexcel.DisplayAlerts = true;
            xlWorkBook.Close(true, misValue, misValue);
            xlexcel.Quit();
    
            releaseObject(xlWorkSheet);
            releaseObject(xlWorkBook);
            releaseObject(xlexcel);
    
            // Clear Clipboard and DataGridView selection
            Clipboard.Clear();
            dgvItems.ClearSelection();
    
            // Open the newly saved excel file
            if (File.Exists(sfd.FileName))
                System.Diagnostics.Process.Start(sfd.FileName);
        }
    }
    
    private void copyAlltoClipboard()
    {
        dgvItems.SelectAll();
        DataObject dataObj = dgvItems.GetClipboardContent();
        if (dataObj != null)
            Clipboard.SetDataObject(dataObj);
    }
    
    private void releaseObject(object obj)
    {
        try
        {
            System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
            obj = null;
        }
        catch (Exception ex)
        {
            obj = null;
            MessageBox.Show("Exception Occurred while releasing object " + ex.ToString());
        }
        finally
        {
            GC.Collect();
        }
    }
    
    0 讨论(0)
  • 2020-11-28 05:36
    using Excel = Microsoft.Office.Interop.Excel;
    
    
    private void btnExportExcel_Click(object sender, EventArgs e)
    {
        try
        {
            Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
            excel.Visible = true;
            Microsoft.Office.Interop.Excel.Workbook workbook = excel.Workbooks.Add(System.Reflection.Missing.Value);
            Microsoft.Office.Interop.Excel.Worksheet sheet1 = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Sheets[1];
            int StartCol = 1;
            int StartRow = 1;
            int j = 0, i = 0;
    
            //Write Headers
            for (j = 0; j < dgvSource.Columns.Count; j++)
            {
                Microsoft.Office.Interop.Excel.Range myRange = (Microsoft.Office.Interop.Excel.Range)sheet1.Cells[StartRow, StartCol + j];
                myRange.Value2 = dgvSource.Columns[j].HeaderText;
            }
    
            StartRow++;
    
            //Write datagridview content
            for (i = 0; i < dgvSource.Rows.Count; i++)
            {
                for (j = 0; j < dgvSource.Columns.Count; j++)
                {
                    try
                    {
                        Microsoft.Office.Interop.Excel.Range myRange = (Microsoft.Office.Interop.Excel.Range)sheet1.Cells[StartRow + i, StartCol + j];
                        myRange.Value2 = dgvSource[j, i].Value == null ? "" : dgvSource[j, i].Value;
                    }
                    catch
                    {
                        ;
                    }
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
    }
    
    0 讨论(0)
  • 2020-11-28 05:36

    The Best is use use closedxml.codeplex.com Library.Refer it @https://closedxml.codeplex.com/wikipage?title=Adding%20DataTable%20as%20Worksheet&referringTitle=Documentation

    var wb = new ClosedXML.Excel.XLWorkbook();
    DataTable dt = GetTheDataTable();//Refer documentation
    
    
    wb.Worksheets.Add(dt);
    
    Response.Clear();
    Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
    Response.AddHeader("content-disposition", "attachment;filename=\"FileName.xlsx\"");
    
    using (var ms = new System.IO.MemoryStream()) {
        wb.SaveAs(ms);
        ms.WriteTo(Response.OutputStream);
        ms.Close();
    }
    
    Response.End();
    
    0 讨论(0)
  • 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);
        }
    
    0 讨论(0)
  • 2020-11-28 05:37

    I did not intend to steal @Jake and @Cornelius's answer, so i tried editing it. but it was rejected. Anyways, the only improvement I have to point out is about avoiding extra blank column in excel after paste. Adding one line dataGridView1.RowHeadersVisible = false; hides so called "Row Header" which appears on the left most part of DataGridView, and so it is not selected and copied to clipboard when you do dataGridView1.SelectAll();

    private void copyAlltoClipboard()
        {
            //to remove the first blank column from datagridview
            dataGridView1.RowHeadersVisible = false;
            dataGridView1.SelectAll();
            DataObject dataObj = dataGridView1.GetClipboardContent();
            if (dataObj != null)
                Clipboard.SetDataObject(dataObj);
        }
        private void button3_Click_1(object sender, EventArgs e)
        {
            copyAlltoClipboard();
            Microsoft.Office.Interop.Excel.Application xlexcel;
            Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
            Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
            object misValue = System.Reflection.Missing.Value;
            xlexcel = new Excel.Application();
            xlexcel.Visible = true;
            xlWorkBook = xlexcel.Workbooks.Add(misValue);
            xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
            Excel.Range CR = (Excel.Range)xlWorkSheet.Cells[1, 1];
            CR.Select();
            xlWorkSheet.PasteSpecial(CR, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, true);          
        }
    
    0 讨论(0)
  • 2020-11-28 05:38

    I'm adding this answer because none of the other methods use OpenXMLWriter, despite the fact that it is faster than OpenXML DOM and both faster and more reliable than COM/Interop, and because some of the other methods use the clipboard, which I would caution against, as it's output is unreliable.

    The details can be found in my answer in the link below, however that example is for a DataTable, but you can adapt it to using a DataGridView by just changing the row/column loops to reference a dgv instead of a dt.

    How to export DataTable to Excel

    0 讨论(0)
提交回复
热议问题