Skip to main content
 首页 » 编程设计

c#之从 Excel 中查找和提取数据

2024年02月24日19rubylouvre

我正在尝试编写一个应用程序,它将打开一个 Excel 电子表格,找到具有正确名称的工作表并遍历行,直到我在第 0 列找到包含文本“Cont Date”的单元格,然后通读直到我找到了第一个空白单元格(也是第 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 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...