2017-10-18 4 views
0

oledbプロバイダを使用せずにExcelシートでselect文を使用するにはどうすればよいですか?これは今まで私がusing Excel = Microsoft.Office.Interop.Excel;を使って得たものです。あなたが範囲にitemsインタフェースを使用することができますが超えるすべてのセルを行くためにOLEDBプロバイダを使用せずにExcelシートでselect文を発行する

// Create excel application object by calling constructor 
Excel.Application xlApp = new Excel.Application(); 

// Open excel file using excel object 
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(@"D:\Temp\file.xls"); 

// Open first sheet within excel document (index start at 1, not 0) 
Excel._Worksheet xlWorksheet = (Excel.Worksheet)xlWorkbook.Sheets["SheetName"]; 

// Get used sheet bounderies 
Excel.Range xlRange = xlWorksheet.UsedRange; 

// Get row count 
int rowCount = xlRange.Rows.Count; 

// Get column count 
int colCount = xlRange.Columns.Count; 

//iterate over the rows and columns and print to the console as it appears in the file 
for (int i = 1; i <= rowCount; i++) 
{ 
    for (int j = 1; j <= colCount; j++) 
    { 
     //new line 
     if (j == 1) 
      Console.Write("\r\n"); 

     //write the value to the console if cell value ends on 'd' 
     if (xlRange.Cells[i, j] != null && xlRange.Cells[i, j].Value2 != null && (xlRange.Cells[i, j].Value2.ToString()).EndsWith("d")) 
      Console.Write(xlRange.Cells[i, j].Value2.ToString() + "\t"); 
    } 
} 
+0

なぜそれが間違っていると感じていますか?各行ごとに異なる処理を行い、各列をテストするにはネストされたループが必要です。ところで、改行の出力を 'for'の内側に移動し、' j'をテストする代わりに 'Console.WriteLine();'を入れてみることができます。 – NetMage

答えて

0

...間違って感じているforループを使用して、ネストされた各セルを反復処理するには、行ごとに出力し、条件付きで列にわたって出力しています、forが適切なアプローチです。

しかし、あなたは少しのコードを引き締めることができます:

var rowCount = xlRange.Rows.Count; 
var colCount = xlRange.Columns.Count; 

for (int row = 1; row <= rowCount; ++row) { 
    Console.WriteLine(); 
    for (int col = 1; col <= colCount; ++col) { 
     //write the value to the console if cell value ends on 'd' 
     if (xlRange.Cells[row, col]?.Value2?.ToString().EndsWith("d") ?? false) 
      Console.Write(xlRange.Cells[row, col].Value2.ToString() + "\t"); 
    } 
} 
関連する問題