Home > Software design >  C# winforms open folder after excel file is exported
C# winforms open folder after excel file is exported

Time:10-13

I am working on C# winforms. I have a gridview in which I am displaying data from database. Also, I am exporting the gridview data to an excel file.

 private void BtnExport_Click(object sender, EventArgs e)
    {
       
        // To start
        Cursor cursor = Cursor.Current;
        Cursor.Current = Cursors.WaitCursor;


        if (!Directory.Exists(dir))
        {
            Directory.CreateDirectory(dir);
        }
        string location = Path.Combine(dir, "Having_Dues_"   name   "_Till_"   date  "_at_"   DateTime.Now.ToString("hh_mm_ss")  ".xlsx");
        ExportToExcel(dtData, location);
        // To finish
        //_longOperation.Stop();
        Cursor.Current = Cursors.Default;
      
    }

    public static void ExportToExcel(DataTable DataTable, string ExcelFilePath = null)
    {
        try
        {
            int ColumnsCount;

            if (DataTable == null || (ColumnsCount = DataTable.Columns.Count) == 0)
                throw new Exception("ExportToExcel: Null or empty input table!\n");

            // load excel, and create a new workbook
            Microsoft.Office.Interop.Excel.Application Excel = new Microsoft.Office.Interop.Excel.Application();
            Excel.Workbooks.Add();

            // single worksheet
            Microsoft.Office.Interop.Excel._Worksheet Worksheet = Excel.ActiveSheet;

            object[] Header = new object[ColumnsCount];

            // column headings               
            for (int i = 0; i < ColumnsCount; i  )
                Header[i] = DataTable.Columns[i].ColumnName;

            Microsoft.Office.Interop.Excel.Range HeaderRange = Worksheet.get_Range((Microsoft.Office.Interop.Excel.Range)(Worksheet.Cells[1, 1]), (Microsoft.Office.Interop.Excel.Range)(Worksheet.Cells[1, ColumnsCount]));
            HeaderRange.Value = Header;
            HeaderRange.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.LightGray);
            HeaderRange.Font.Bold = true;

            // DataCells
            int RowsCount = DataTable.Rows.Count;
            object[,] Cells = new object[RowsCount, ColumnsCount];

            for (int j = 0; j < RowsCount; j  )
                for (int i = 0; i < ColumnsCount; i  )
                    Cells[j, i] = DataTable.Rows[j][i];

            Worksheet.get_Range((Microsoft.Office.Interop.Excel.Range)(Worksheet.Cells[2, 1]), (Microsoft.Office.Interop.Excel.Range)(Worksheet.Cells[RowsCount   1, ColumnsCount])).Value = Cells;

            // check fielpath
            if (ExcelFilePath != null && ExcelFilePath != "")
            {
                try
                {
                    Worksheet.SaveAs(ExcelFilePath);
                    Excel.Quit();
                    MessageBox.Show("Excel file saved at "  ExcelFilePath);
                }
                catch (Exception ex)
                {
                    throw new Exception("ExportToExcel: Excel file could not be saved! Check filepath.\n"
                          ex.Message);
                }
            }
            else    // no filepath is given
            {
                Excel.Visible = true;
            }
        }
        catch (Exception ex)
        {
            throw new Exception("ExportToExcel: \n"   ex.Message);
        }
    }

enter image description here

I am successfully able to export the data to an excel file.

Now I want, after exporting the data to an excel file I want to open the folder in which the file is saved. i.e. after clicking on the OK button, it will open the folder where the excel file is saved.

How to do this? Any help would be highly appreciated.

CodePudding user response:

You need to use ProcessStart and launch explorer.exe and pass the path into it.

        //first we extract the path from the full file name
        var dir = Path.GetDirectoryName(ExcelFilePath);


        //Now we launch and pass this as an argument
        ProcessStartInfo startInfo = new ProcessStartInfo
        {
            FileName = "explorer.exe",
            Arguments = "\""   dir   "\""
        };
        Process.Start(startInfo);

BTW, if you want to launch excel directly with the file then you follow the same process but change from explorer.exe to Excel.exe.

  • Related