2017-03-03 75 views
1

此代碼正常工作。但是當我想改變範圍時,給出OleDBException。C#Excel查詢問題

OleDbCommand dates = new OleDbCommand("SELECT date FROM ["Sheet1$A1:B150"] ", baglanti); 
OleDbDataReader reader= dates.ExecuteReader(); 
while (reader.Read()) 
{ 
    list.Add(reader["date"]); 
} 

範圍內變化的版本:

OleDbCommand dates = new OleDbCommand("SELECT date FROM ["Sheet1$A250:B350"] ", baglanti); 
OleDbDataReader reader= dates.ExecuteReader(); 

while (reader.Read()) 
{ 
    list.Add(reader["date"]); 
} 

的例外是:

System.Data.OleDb.OleDbException was unhandled by user code 
ErrorCode=-2147217904 
HResult=-2147217904 
Message=No value is entered for one or more required parameters. 
Source=Microsoft Access Database Engine 
StackTrace: 
konum: System.Data.OleDb.OleDbCommand.ExecuteCommandTextErrorHandling(OleDbHResult hr) 
konum: System.Data.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult(tagDBPARAMS dbParams, Object& executeResult) 
konum: System.Data.OleDb.OleDbCommand.ExecuteCommandText(Object& executeResult) 
konum: System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior behavior, String method) 
konum: System.Data.OleDb.OleDbCommand.ExecuteReader(CommandBehavior behavior) 
konum: Hasta_Bulucu.Form1.bul_DoWork(Object sender, DoWorkEventArgs e) C:\Users\Furka\documents\visual studio 2015\Projects\Hasta Bulucu\Hasta  Bulucu\Form1.cs içinde: satır 269 
konum: System.ComponentModel.BackgroundWorker.OnDoWork(DoWorkEventArgs e) 
konum: System.ComponentModel.BackgroundWorker.WorkerThreadStart(Object argument) 
InnerException: 
+0

請問您可以添加您用來初始化OledDbConnection的連接字符串嗎? – andrews

+0

@andrews OleDbConnection baglanti = new OleDbConnection(@「Provider = Microsoft.ACE.OLEDB.12.0; Data Source =」+ filePick.FileName.ToString()+「; Mode = Read; Extended Properties ='Excel 12.0 xml; HDR = YES; IMEX = 1;'「); –

+0

@andrews當我將範圍A1設置爲R250時,它包含工作表的標題,但A150至R300不包括標題。所以sql命令找不到列名。我需要在這個選項中包含標題信息。那麼該怎麼做呢? –

回答

1

嘗試以下操作:

設置HDR=NO在連接字符串中,如:

OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + 
         filePick.FileName.ToString() + 
";Mode=Read;Extended Properties='Excel 12.0 xml;HDR=NO;IMEX=1;'"); 

也嘗試將IMEX設置爲0和2並嘗試使用HDR = NO的不同組合。

如果範圍不包括列名稱,則可能會出錯。因此,您需要嘗試按列索引讀取文件,而不是名稱。

+0

列索引的想法是有道理的。但我堅持在SQL。我不能通過columnID查詢像A,B,C ....我試着從[Sheet1 $]選擇一個,但仍然會拋出異常(HDR = NO)@andrews –

+0

@FK是的,我想過但沒有能力找到任何樣品。如果您嘗試使用R1C1符號怎麼辦?或者按照索引'[1]'查詢列。還要做'SELECT *'並在調試器中打開結果集,並嘗試查看那裏的列/字段名稱。 – andrews

+0

@adrews終於完成了。它必須是F1 ..... Fn不是直接的列名,如A,B等。再次感謝你。 –