Search code examples
c#winformsexceldatagridexport-to-excel

Export datagrid to Excel using Dialog Box on Winform


I'm looking for how to export a datagrid (or dataSet) (not datagridview) to Excel using dialog box which saves data in specific place, I am working on VS 2003 Winform not Webform.

This is my code:

I just need too open a dialog box to let the user choose where he wants to put his file:

private void button2_Click(object sender, System.EventArgs e)
        {
#region
                string data = null;
                int i = 0;
                int j = 0; 

                Excel.Application xlApp ;
                Excel.Workbook xlWorkBook ;
                Excel.Worksheet xlWorkSheet ;
                object misValue = System.Reflection.Missing.Value;

                xlApp = new Excel.ApplicationClass();
                xlWorkBook = xlApp.Workbooks.Add(misValue);
                xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

                for (i = 0; i <= dsSelectionListeDiffere.Tables[0].Rows.Count - 1; i++)
                {
                    for (j = 0; j <= dsSelectionListeDiffere.Tables[0].Columns.Count - 1; j++)
                    {
                        data = dsSelectionListeDiffere.Tables[0].Rows[i].ItemArray[j].ToString();
                        xlWorkSheet.Cells[i + 1, j + 1] = data;
                    }
                }

                xlWorkBook.SaveAs("csharp.net-informations.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
                xlWorkBook.Close(true, misValue, misValue);
                xlApp.Quit();

                releaseObject(xlWorkSheet);
                releaseObject(xlWorkBook);
                releaseObject(xlApp);

                MessageBox.Show("Excel file created , you can find the file c:\\csharp.net-informations.xls");
#endregion
}

and i have another code it works too :

#region
////            lblMessage.Visible = true;
////            lblMessage.Text = "";
//          // Export all the details
//          try
//          {           
//              // Get the datatable to export          
//              DataTable dt = dsSelectionListeDiffere.Tables[0].Copy();
//              dsSelectionListeDiffere = FrmFonctionPrincipale.getListeDifferesParClient(1);
//              // Export all the details to Excel
//
//
//              RKLib.ExportData.Export objExport = new RKLib.ExportData.Export("Win");             
//              objExport.ExportDetails(dt, Export.ExportFormat.Excel, "C:\\EmployeesInfo.xls");
//              MessageBox.Show("Exporté Avec Succès dans  C:\\EmployeesInfo.xls");
//          }
//          catch(Exception Ex)
//          {
//              MessageBox.Show(Ex.Message);
////                lblMessage.Text = Ex.Message;
//          }
        #endregion

Solution

  • If you don't need to change the filename, but only the folder where this file is saved, then you can use the FolderBrowserDialog to ask just the folder where the file will be saved

    private void button2_Click(object sender, System.EventArgs e)
    {
        FolderBrowserDialog fbd = new FolderBrowserDialog();
        fbd.Description = "Select the destination folder";
        fbd.ShowNewFolderButton = true;
        fbd.RootFolder = Environment.SpecialFolder.Personal;
        if( fbd.ShowDialog() == DialogResult.OK )
        {
            string folderName = fbd.SelectedPath;
            .... the rest of your excel export code .....
    
            // Pass the full path to the SaveAs method
            string fullPathName = Path.Combine(folderName, "csharp.net-informations.xls");
            xlWorkBook.SaveAs(fullPathName, .....);
    
            .....
    
            MessageBox.Show("Excel file created , you can find the file in: " + fullPathName);
       }
    

    If you need to change also the file name, then you need to use a SaveFileDialog instance.

     SaveFileDialog sfd = new SaveFileDialog();
     sfd.Filter = "Excel files (*.xls)|*.xls|All files (*.*)|*.*"  ;
     sfd.FilterIndex = 1 ;
     sfd.RestoreDirectory = true ;
     sfd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
     if(sfd.ShowDialog() == DialogResult.OK)
     {
         if(sfd.FileName.Length > 0)
         {
            ... the rest of your excel code here ....
    
            // sfd.FileName already contains the full path so
            xlWorkBook.SaveAs(sfd.FileName, .....);
    
         }
     }
     else
     {
          if(MessageBox.Show("Are you sure you want to quit without saving?", "Quitting",
                             MessageBoxButtons.YesNo) == DialogResult.No)
          {
              // This important to stop the Form to close if this button is the Cancel/AcceptButton
              // or its property DialogResult is not DialogResult.None
              this.DialogResult = DialogResult.None;
          }
     }