C# winforms 在 excel 文件导出后打开文件夹

C# winforms open folder after excel file is exported

我正在研究 C# winforms。我有一个 gridview,我在其中显示来自 database 的数据。另外,我正在将 gridview 数据导出到 excel 文件。

 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);
        }
    }

我能够成功地将数据导出到 excel 文件。

现在我想,在将数据导出到 excel 文件后,我想打开保存文件的文件夹。即点击 OK 按钮后,它将打开保存 excel 文件的文件夹。

如何做到这一点?任何帮助将不胜感激。

您需要使用 ProcessStart 并启动 explorer.exe 并将路径传递给它。

        //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);

顺便说一句,如果你想直接用文件启动 excel 那么你遵循相同的过程,但从 explorer.exe 更改为 Excel.exe。