我嘗試使用oledb獲取excel表名。我從使用OleDb的Excel文件中獲取無效的工作表名稱。怎麼了?
我的連接字符串是:
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
filepath +
";Extended Properties=Excel 12.0;";
其中filepath
是一個文件名。
我給這家代碼:
List<string> sheetNames = new List<string>();
_excel.Connect(_path);
DataTable dataTable = _excel.ExecuteSchema();
_excel.Disconnect();
foreach (DataRow row in dataTable.Rows)
{
string sheetName = row["TABLE_NAME"].ToString();
if(!sheetName.EndsWith("$'")) { continue; }
sheetNames.Add(sheetName);
}
列表與表名稱包含了所有有效工作表名稱和一些其他的工作表名稱。 例子:
"'correctsheetname$'"
-
我只補充一點,在$'
我的問題是端片,如果工作表名稱包含一個單引號,我有兩個得到它單引號。
例子: 名爲asheetname's
片我得到'asheetname''s$''
之後,當我試圖讓這個表的數據源,我得到一個例外,這個表不存在。
query = "SELECT * FROM ['asheetname''s$']"
_command = new OleDbCommand(query, _connection);
_dataTable = new DataTable();
_dataReader = _command.ExecuteReader(); <-- Exception is thrown here
和異常消息:
{System.Data.OleDb.OleDbException: ''asheetname''s$'' is not a valid name. Make sure that it does not include invalid characters or punctuation and that it is not too long. at System.Data.OleDb.OleDbCommand.ExecuteCommandTextErrorHandling(OleDbHResult hr) at System.Data.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult(tagDBPARAMS dbParams, Object& executeResult) at System.Data.OleDb.OleDbCommand.ExecuteCommandText(Object& executeResult) at System.Data.OleDb.OleDbCommand.ExecuteCommand(CommandBehavior behavior, Object& executeResult) at System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior behavior, String method) at System.Data.OleDb.OleDbCommand.ExecuteReader(CommandBehavior behavior) at System.Data.OleDb.OleDbCommand.ExecuteReader() at PrestaImporter.Entity.Excel.ExecuteQuery(String query)
使用一種方法來確定名稱是否包含引號,然後從名稱中提取多餘的引號。 – 2011-12-15 09:28:03
這是官方的方式嗎? – ddarellis 2011-12-15 09:29:48