Tag Archives: DataGridView to EXCEL

How to Export All data in DataGridView to Local Excel

Export all data in DataGridView to local excel

When the method is called, the parameter can be written into its own DataGridView name

 #region DataGridView Export to local Excel file method
        public void DownloadDataGridView(DataGridView dgv)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog
            {
                Filter = "Execl files (*.xls)|*.xls",
                FilterIndex = 0,
                RestoreDirectory = true,
                CreatePrompt = true,
                Title = "Exported Excel"
            };
            saveFileDialog.ShowDialog();
            if (saveFileDialog.FileName == "")
            {
                return;
            }//end if
            Stream myStream = saveFileDialog.OpenFile();
            //use the default encode
            StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0));
            string str = "";
            try
            {
                for (int i = 0; i < dgv.ColumnCount; i++)
                {
                    str += dgv.Columns[i].HeaderText;
                    str += "\t";
                }//end for
                sw.WriteLine(str);
                for (int j = 0; j < dgv.Rows.Count - 1; j++)
                {
                    string strTemp = "";
                    for (int k = 0; k < dgv.Columns.Count; k++)
                    {
                        object obj = dgv.Rows[j].Cells[k].Value;
                        if (obj != null)
                        {
                            strTemp += dgv.Rows[j].Cells[k].Value.ToString();
                        }//end if
                        else
                        {
                            strTemp = "";
                        }//end else
                        strTemp += "\t";
                    }//end for k
                    sw.WriteLine(strTemp);
                }//end for j
                sw.Close();
                myStream.Close();
                MessageBox.Show("Success to Export the Excel Fileļ¼š\n" + saveFileDialog.FileName);
            }//end try
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }//end catch
            finally
            {
                sw.Close();
                myStream.Close();
            }//end finally
        }
        #endregion