2010-10-14 95 views
0

我想寫一個應用程序,它將打開一個excel電子表格找到正確名稱的工作表並遍歷行,直到找到包含文本的第0列單元格爲止「Cont Date 「然後閱讀,直到找到第一個空白單元格(第0列)。我越來越掛在如何遍歷行。從Excel中查找和提取數據

這是我到目前爲止有:

public static void LoadFromFile(FileInfo fi) 
{ 
    Application ExcelObj = new Application(); 

    if (ExcelObj != null) 
    { 
     Workbook wb = ExcelObj.Workbooks.Open(fi.FullName, 
      Type.Missing, true, Type.Missing, Type.Missing, 
      Type.Missing, Type.Missing, Type.Missing, Type.Missing, 
      Type.Missing, Type.Missing, Type.Missing, Type.Missing, 
      Type.Missing, Type.Missing); 

     Sheets sheets = wb.Worksheets; 

     foreach (Worksheet ws in sheets) 
     { 
      if (ws.Name == "Raw Data") 
       LoadFromWorkSheet(ws); 
     } 

     wb.Close(false, Type.Missing, Type.Missing); 
    } 
} 

public static void LoadFromWorkSheet(Worksheet ws) 
{ 
    int start = 0; 
    int end = 0; 

    // Iterate through all rows at column 0 and find the cell with "Cont Date" 
} 

顯然,你不能

foreach(Row row in worksheet.Rows) 
{ 

} 

編輯::

我所做的就是這是什麼:

for (int r = 0; r < 65536; r++) 
{ 
    string value = ws.Cells[r, 0].Value; 
} 

這給了我以下的exce ption當試圖讀取單元格的值:

Exception from HRESULT: 0x800A03EC 
+1

不,它必須是ws.Cells [r,1]。列以1開頭 – 2010-10-14 20:24:17

回答

2

您可以使用單元格屬性,因爲列從1開始,我認爲你的意思列1:

int contDateRow=0; 
int firstBlankRowAfterContDate=0; 

for (int row=1;row<=woksheet.Rows.Count;++row) 
    if (worksheet.Cells[row,1].Value=="Cont Date") 
    { 
    contDateRow=row; 
    break; 
    } 

if (contDateRow!=0) 
{ 
    for (int row=contDateRow;row<=woksheet.Rows.Count;++row) 
    if (worksheet.Cells[row,1].Value=="") 
    { 
     firstBlankRowAfterContDate=row; 
     break; 
    } 
} 

// Do something with contDateRow and firstBlankRowAfterContDate... 
+0

請參閱OP中關於我得到的例外的編輯: – 2010-10-14 17:49:48

1

OK ......一個幾件事...

首先,讓自己一個「範圍」來處理。爲了您的目的,試試這個:

Microsoft.Office.Interop.Excel range = worksheet.get_Range("A1"); 

現在,你有你的範圍,你可以找到每列的程度,用的功能行,像這樣:

private Point GetSheetBounds(Excel.Range range) 
{ 
    int maxY = range.get_End(Excel.XlDirection.xlDown).Row; 
    int maxX = range.get_End(Excel.XlDirection.xlToRight).Column; 

    return new Point(maxX, maxY); 
} 

這將告訴你如何遠遠不得不循環,這樣你就不會從0到無限。 :P

現在,你可以通過做行這樣的循環中的列:

for (int i = 1; i < this.GetSheetBounds(range).Y; i++) //i = 1 because Excel doesn't use zero-based indexes 
{ 
    if (range[i, 1] != null && range[i, 1].Value != null && range[i, 1].Value == "Cont Date") 
    { 
     //do whatever you need to do 
    } 
} 

最後,當你使用COM,請確保您處理你的函數一種創造一切像這樣:

private void ReleaseObject(object obj) 
{ 
    if (obj != null) 
    { 
     System.Runtime.InteropServices.Marshal.ReleaseComObject(obj); 
     obj = null; 
     GC.Collect(); 
    } 
}