从Excel中查找和提取数据

我试图编写一个应用程序,将打开一个Excel电子表格find正确的名称的工作表,并遍历行,直到我find包含文本“Cont Date”0列的单元格,然后通读,直到我find第一个空白单元格(第0列)。 我越来越挂在如何遍历行。

以下是我到目前为止:

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; } 

当试图读取单元格的值时,给了我下面的exception:

 Exception from HRESULT: 0x800A03EC 

你可以使用Cells属性,因为列从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... 

好的…几件事…

首先,让自己一个“范围”的工作。 为了您的目的,试试这个:

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

现在你已经有了你的范围,你可以用函数find每一列和每一行的范围,如下所示:

 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); } 

这将告诉你,你有多less回路,以便你不会从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时,确保你用类似这样的函数来处理你创build的所有东西:

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