OleDbConnection Source Variable in C#

ぃ、小莉子 提交于 2021-02-20 03:49:46

问题


How can I replace D:\temp\test.xls with filePath in OleDbConnection statement.

I can get the exactly filePath (with OpenFileDialog, then I can located my .xls file conveniently, no more hardcoded), but when I insert the variable filePath as Style2, it doesn't work. How can I fix this ? Thanks.

Style1

OleDbConnection dbConnection = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\temp\test.xls;Extended Properties=""Excel 8.0;HDR=Yes;""");

Style2

OleDbConnection dbConnection = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=filePath;Extended Properties=""Excel 8.0;HDR=Yes;""");

[Updated] Some part of my code as this,

DataTable fooData = new DataTable();

            OleDbConnection dbConnection = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=filePath;Extended Properties=""Excel 8.0;HDR=Yes;""");

            dbConnection.Open ();
            try
            {
                OleDbCommand dbCommand = new OleDbCommand("SELECT * FROM [maleSheet$]", dbConnection);
                OleDbDataReader dbReader = dbCommand.ExecuteReader();

                int RankIndex = dbReader.GetOrdinal("Rank");

                while (dbReader.Read())
                {
                    string rank = dbReader.GetValue(RankIndex).ToString();
                    ////....
                }
           }

Error as below at line OleDbDataReader dbReader = dbCommand.ExecuteReader();

An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll


回答1:


OleDbConnection dbConnection = new OleDbConnection( String.Format( @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=""Excel 8.0;HDR=Yes;""", filePath ) );


来源:https://stackoverflow.com/questions/5775648/oledbconnection-source-variable-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!