首页 > 解决方案 > 如何读取文件夹下的excel文件名和扩展名(xls,xlsx)?

问题描述

是否可以读取文件夹下的所有 excel 文件名和 ext(xls,xlsx)?

这是文件夹名称,我想读取所有 excel 文件名和 ext(xls,xlsx)

下面的代码是我尝试过的,但我想用 ext 读取所有文件名。任何人都可以给出最好的建议来获得解决方案。

    private static void ReadExcelFileSheetWithOleDb()
    {
        //Microsoft.Jet.OLEDB.4.0   --- Microsoft.ACE.OLEDB.12.0
        //D:\\List_of_cid.xlsx

        string con = string.Empty;

        //string ext = Path.GetExtension("./Excel_Folder/List_of_cid.xlsx").ToLower();
        //string path = Path.GetFullPath("~/Excel_Folder/").ToString();

        //string[] fileArrayxls = Directory.GetFiles(@"~\Excel_Folder\", "*.xls");
        //string[] fileArrayxlsx = Directory.GetFiles(@"~\Excel_Folder\", "*.xlsx");
        

        string ext = Path.GetExtension("D:\\List_of_cid.xlsx").ToLower();
        

       
        if (ext.Trim() == ".xls")
        {
            // con = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + "; Extended Properties='Excel 8.0;HDR=YES;IMEX=1;'";

            con = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\\List_of_cid.xlsx; Extended Properties='Excel 8.0;HDR=YES;IMEX=1;'";
        }
        else if (ext.Trim() == ".xlsx")
        {
            con = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\\List_of_cid.xlsx; Extended Properties='Excel 8.0;HDR=YES;IMEX=1;'";
        }

        using (OleDbConnection oledbConn = new OleDbConnection(con))
        {
            // OleDbConnection oledbConn = new OleDbConnection(connString);
            try
            {

                oledbConn.Open();

                OleDbCommand cmd = new OleDbCommand("SELECT * FROM [Sheet1$]", oledbConn);

                OleDbDataAdapter oleda = new OleDbDataAdapter();

                oleda.SelectCommand = cmd;

                DataSet ds = new DataSet();

                oleda.Fill(ds, "List_of_cid");

                foreach (var m in ds.Tables[0].DefaultView)
                {
                    Console.WriteLine(((DataRowView)m).Row.ItemArray[0] + " " + ((DataRowView)m).Row.ItemArray[1]);

                }

                // oledbConn.Close();

            }
            catch (Exception e)
            {
                Console.WriteLine("Error :" + e.Message);
            }
        }
    }

我是编码新手。

标签: c#console-application

解决方案


推荐阅读