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

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

    In my opinion this is the easiest and instantly working method of exporting datagridview.

     try
            {
                SaveFileDialog sfd = new SaveFileDialog();
                sfd.Filter = "Excel Documents (*.xlsx)|*.xlsx";
                sfd.FileName = "ProfitLoss.xlsx";
                if (sfd.ShowDialog() == DialogResult.OK)
                {
                    DataTable dts = new DataTable();
                    for (int i = 0; i < grdProfitAndLoss.Columns.Count; i++)
                    {
                        dts.Columns.Add(grdProfitAndLoss.Columns[i].Name);
                    }
                    for (int j = 0; j < grdProfitAndLoss.Rows.Count; j++)
                    {
                        DataRow toInsert = dts.NewRow();
                        int k = 0;
                        int inc = 0;
                        for (k = 0; k < grdProfitAndLoss.Columns.Count; k++)
                        {
                            if (grdProfitAndLoss.Columns[k].Visible == false) { continue; }
                            toInsert[inc] = grdProfitAndLoss.Rows[j].Cells[k].Value;
                            inc++;
                        }
                        dts.Rows.Add(toInsert);
                    }
                    dts.AcceptChanges();
                    ExcelUtlity obj = new ExcelUtlity();
                    obj.WriteDataTableToExcel(dts, "Profit And Loss", sfd.FileName, "Profit And Loss");
                    MessageBox.Show("Exported Successfully");
                }
            }
            catch (Exception ex)
            {
    
            }
    

提交回复
热议问题