2012-10-17 103 views
0

我需要编写一个sql查询(在c#中)选择Excel表格数据只有从C19开始的“C”列。但我不能指定结束单元格编号,因为更多的数据被添加到列中。因此,我需要知道如何指定列的结尾。请帮忙。我提到了我正在使用的查询。我附上了我使用的Excel表格的图像!并附上了输出datagridview!SQL查询选择一个范围

//Generte Oracle Datatable 
      OleDbConnection conn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;" 
      + @"Data Source=" + textBox1.Text + ";" + @"Extended Properties=""Excel 12.0 Macro;HDR=Yes"""); 
      conn.Open(); 

      OleDbCommand ccmd = new OleDbCommand(@"Select * From [SPAT$]", conn); 
      OleDbDataAdapter adapter = new OleDbDataAdapter(ccmd);      
      DataTable Oracle = new DataTable(); 
      adapter.Fill(Oracle); 

      for (int y = 19; y < Oracle.Rows.Count; y++) 
      { 
       var value = Oracle.Rows[y][3].ToString();   
      } 
      dataGridView1.DataSource = Oracle.AsEnumerable().Where((row, index) => index > 3).CopyToDataTable();     
+0

相关:http://stackoverflow.com/questions/368505/is-it-possible-to-select-sql-server-data-using-column -ordinal-position – twodayslate

+0

我不认为它是相关的.. – manas

回答

1

第一方法中,使用OLE查询:

OleDbCommand ccmd = new OleDbCommand(@"Select * From [SPAT$]", conn); 
OleDbDataAdapter da = new OleDbDataAdapter(ccmd); 
DataTable dt = new DataTable(); 
da.Fill(dt); 

for (int i = 19; i < dt.Rows.Count; i++) 
{ 
    var value = dt.Rows[i][3].ToString(); // here 3 refers to column 'C' 
} 

对于标准的基于数据表

dataGridView1.DataSource = dt.AsEnumerable() 
          .Where((row, index) => index >= 19) 
          .CopyToDataTable(); 

对于Column “C” 只

dataGridView1.DataSource = dt.AsEnumerable() 
         .Where((row, index) => index >= 19) 
         .Select(t => t[3].ToString()).ToList(); 

第二种方法中,使用Excel的COM对象:

using Excel = Microsoft.Office.Interop.Excel; 

Excel.Application xlApp = new Excel.Application(); 
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open("path to book"); 
Excel.Worksheet xlSheet = xlWorkbook.Sheets[1]; // get first sheet 
Excel.Range xlRange = xlSheet.UsedRange; // get the entire used range 

int numberOfRows = xlRange.Rows.Count; 

List<string> columnValue = new List<string>(); 
// loop over each column number and add results to the list 

int c = 3; // Column 'C' 
for(int r = 19; r <= numberOfRows; r++) 
{ 
    if(xlRange.Cells[r,c].Value2 != null) // ADDED IN EDIT 
    { 
     columnValue.Add(xlRange.Cells[r,c].Value2.ToString()); 
    } 
} 
+0

谢谢。我附加了Excel表格并插入了查询。请帮忙 –

+0

你是否应用了这种条件,其中((行,索引)=>索引> = 19)写在答案中? –

+0

我纠正它并执行该程序。现在它显示第23行的所有列。我附上了新的输出。但我需要从第20列(第1行)的行。我想第19列作为标题,但可以忽略。无论如何,我纠正了我= 16,现在我可以从第19行获得列。你能帮我得到只有列“C”数据 –