我正在尝试编写一个打开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)
{
}
EDIT ::
我做的是:
for (int r = 0; r < 65536; r++)
{
string value = ws.Cells[r, 0].Value;
}
在尝试读取单元格的值时会出现以下异常:
Exception from HRESULT: 0x800A03EC
答案 0 :(得分:3)
您可以使用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...
答案 1 :(得分:1)
好的......一些事情......
首先,让自己一个“范围”来使用。为了您的目的,试试这个:
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();
}
}