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

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

    I like Jake's solution. The problem with no header is resolved by doing the following

    xlWorkSheet.Cells[1, 1] = "Header 1";
    xlWorkSheet.Cells[1, 2] = "Header 2";
    xlWorkSheet.Cells[1, 3] = "Header 3";
    

    of course this only works is you know what the headers should be ahead of time.

    0 讨论(0)
  • 2020-11-28 05:25

    Interop is slow and has other issues, using the the clipboard seems non extensible. Here are two other ways to do this

    1. Work with Excel 2007+ files directly instead of working with Excel, it'll be much (much) faster. You can use OpenXML (http://openxmldeveloper.org/) which is Microsoft's SDK. The best way to learn OpenXML is to download the Productivity tool (http://www.microsoft.com/en-us/download/details.aspx?id=5124), ittakes an existing file and generates the code required to create it. Another, perhaps simpler, option is to use ClosedXML (http://closedxml.codeplex.com/). It seems a lot easier to use (look at the example http://closedxml.codeplex.com/wikipage?title=Showcase&referringTitle=Home), but I have no experience with it. I'm sure there are other libraries that wrap work with Excel.

    2. Work with excel via OLEDB. This allows you to work with Excel as if it's a dababase. See http://www.codeproject.com/Articles/8500/Reading-and-Writing-Excel-using-OLEDB or Performance of OLEDB to read Excel for examples and more details.

    I'd start with ClosedXML.

    0 讨论(0)
  • 2020-11-28 05:27

    If your DataGridView's RightToLeft set to Yes then your data copy reversely. So you should use the below code to copy the data correctly.

    private void copyAlltoClipboard()
    {
        dgvItems.RightToLeft = RightToLeft.No;
        dgvItems.SelectAll();
        DataObject dataObj = dgvItems.GetClipboardContent();
        if (dataObj != null)
            Clipboard.SetDataObject(dataObj);
        dgvItems.RightToLeft = RightToLeft.Yes;
    }
    
    0 讨论(0)
  • 2020-11-28 05:28

    I solved this by simple copy and paste method. I don't know it is the best way to do this but,for me it works good and almost instantaneously. Here is my code.

        private void copyAlltoClipboard()
        {
            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);          
        }
    

    Thanks.

    0 讨论(0)
  • 2020-11-28 05:30

    alternatively you can perform a fast export without using Office dll, as Excel can parse csv files without problems.

    Doing something like this (for less than 65.536 rows with titles):

      Try
    
                If (p_oGrid.RowCount = 0) Then
                    MsgBox("No data", MsgBoxStyle.Information, "App")
                    Exit Sub
                End If
    
                Cursor.Current = Cursors.WaitCursor
    
                Dim sText As New System.Text.StringBuilder
                Dim sTmp As String
                Dim aVisibleData As New List(Of String)
    
                For iAuxRow As Integer = 0 To p_oGrid.Columns.Count - 1
                    If p_oGrid.Columns(iAuxRow).Visible Then
                        aVisibleData.Add(p_oGrid.Columns(iAuxRow).Name)
                        sText.Append(p_oGrid.Columns(iAuxRow).HeaderText.ToUpper)
                        sText.Append(";")
                    End If
                Next
                sText.AppendLine()
    
                For iAuxRow As Integer = 0 To p_oGrid.RowCount - 1
                    Dim oRow As DataGridViewRow = p_oGrid.Rows(iAuxRow)
                    For Each sCol As String In aVisibleData
                        Dim sVal As String
                        sVal = oRow.Cells(sCol).Value.ToString()
                        sText.Append(sVal.Replace(";", ",").Replace(vbCrLf, " ; "))
                        sText.Append(";")
                    Next
                    sText.AppendLine()
                Next
    
                sTmp = IO.Path.GetTempFileName & ".csv"
                IO.File.WriteAllText(sTmp, sText.ToString, System.Text.Encoding.UTF8)
                sText = Nothing
    
                Process.Start(sTmp)
    
            Catch ex As Exception
                process_error(ex)
            Finally
                Cursor.Current = Cursors.Default
            End Try
    
    0 讨论(0)
  • 2020-11-28 05:31

    that's what i use for my gridview, try to use it for yr data , it works perfectly :

            GridView1.AllowPaging = false;
            GridView1.DataBind();
    
            StringBuilder sb = new StringBuilder();
    
            for (int k = 0; k < GridView1.Columns.Count; k++)
            {
                //add separator
                sb.Append(GridView1.Columns[k].HeaderText+";");
    
            }
    
    
            //append new line
            sb.Append("\r\n");
            for (int i = 0; i < GridView1.Rows.Count; i++)
            {
                for (int k = 0; k < GridView1.Columns.Count; k++)
                {
                    sb.Append(GridView1.Rows[i].Cells[k].Text+";");
                }
                sb.AppendLine();
            }
    
    0 讨论(0)
提交回复
热议问题