C# 打开指定文件夹或者文件 导入Excel

来源:互联网 发布:部落冲突蓝胖升级数据 编辑:程序博客网 时间:2024/05/22 16:43

打开文件夹: sfd为SaveFileDialog的实例

 System.Diagnostics.Process.Start("explorer.exe",sfd.FileName.Substring(0,sfd.FileName.LastIndexOf(@"\")));

打开指定路径的文件:

 System.Diagnostics.Process.Start("explorer.exe", "/select, " + sfd.FileName);

 

“打开指定路径的文件夹,并选中某个文件”不可与“打开文件夹”一起使用,如果两个语句一起执行,就不会选择文件。 而且无须这么做,因为打开指定路径的文件就默认打开文件夹了。

 

System.Diagnostics.Process.Start("cmd.exe");//可以直接运行windows程序,还有很多其他效果,只要能在运行里面执行的方法应该都可以使用这个来进行执行.

 

 

 

private System.Windows.Forms.OpenFileDialog ofd_Scanner;

ofd_Scanner = new OpenFileDialog();
            ofd_Scanner.InitialDirectory = System.Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
            ofd_Scanner.FileName = "";  //设置对话框打开时获得到的文件名
            ofd_Scanner.RestoreDirectory = true;  //对话框关闭时还原当前目录
            ofd_Scanner.Filter = "表格文件 (*.xls)|*.xls";  //文件筛选器

            //用户选择好文件之后,读取文件内容
            if (ofd_Scanner.ShowDialog() == DialogResult.OK)
            {
                //读取Excel文件内容
                DataSet ds = new DataSet("excel");    //创建ds结果集
                string strCon = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=Excel 8.0;", ofd_Scanner.FileName); //声明连接字符串
                OleDbConnection con = new OleDbConnection(strCon);      //创建连接对象
                con.Open();//打开数据库连接
                DataTable dt = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new[] { null, null, null, "Table" });//检索Excel的架构信息
                var sheet = new string[dt.Rows.Count];
                for (int i = 0, j = dt.Rows.Count; i < j; i++)
                {
                    sheet[i] = dt.Rows[i]["TABLE_NAME"].ToString();
                }
                OleDbDataAdapter adapter = new OleDbDataAdapter(string.Format("select * from [{0}]", sheet[0]), con);  //适配器
                adapter.Fill(ds);//填充数据集

                //将数据集显示在DataGridView上
                //dgv_DataView.DataSource = ds.Tables[0];

                #region 数据赋值
                txtISGID.Text =(string)ds.Tables[0].Rows[0][0];
                #endregion

                con.Close(); //关闭数据库
            }

原创粉丝点击