[英]C# iterate over a row in Excel
I need to iterate over a specific excel row. 我需要遍历特定的Excel行。 For now I've got a code to iterate over a column and I want it to be similar to that.
现在,我有一个代码可以遍历一列,我希望它与之相似。 It looks like this:
看起来像这样:
int columnLength = xlWorkSheet.UsedRange.Rows.Count;
string lastCell = Regex.Replace(CONST_FIRST_CELL, @"\d+", columnLength.ToString()); //will give me the last cell in the column
var excelColumn = xlWorkSheet.Range[CONST_FIRST_CELL, lastCell ];
if (excelColumn == null)
{
throw new Exception("bad col");
}
for (int i = 1; i < columnLength ; i++)
{
Excel.Range currentValue = excelColumn [i];
....DO SOME STUFF....
}
how can I iterate over a specific row? 如何遍历特定行? I'm not sure how to get the last column like I got the last row cell in the above implementation since then I just had to switch a number with the length but now I somehow need to get the correct last cell of a row (which means switching the letters somehow ie C4 to AD4) in order to get the range of first cell row and last...
我不确定如何像在上述实现中获取最后一个行单元格一样获取最后一列,因为那时我只需要切换长度的数字,但是现在我需要以某种方式获取行的正确最后一个单元格(即表示以某种方式切换字母,例如C4到AD4),以获得第一个单元格行和最后一个单元格的范围...
The best solution I guess involves a foreach loop somehow? 我猜最好的解决方案以某种方式涉及到foreach循环?
You were almost there, your loop just needs some tuning: 您快到了,您的循环只需要进行一些调整:
//Input all the Int values you want
int targetRow = 1;
int startCol = 1;
int maxCol = 10; //With this value the loop below will iterate until column 9 (inclusive)
for (int i = startCol; i < maxCol ; i++)
{
Excel.Range currentRange = (Excel.Range)xlWorkSheet.Cells[targetRow, i];
if (currentRange.Value2 != null)
{
string curVal = currentRange.Value2.ToString();
}
}
IMO this is the best way to iterate through cells (by considering rows and/or columns). IMO这是遍历单元格的最佳方法(考虑行和/或列)。 You can do it differently (on the lines of what you were trying): iterating within the columns of a given range (you would need to define the range as
Excel.Range
Type and then rely on the in-built property Columns
), although I think that this can be more confusing. 您可以做不同的事情(按照您尝试的方式):在给定范围的列中进行迭代(您需要将范围定义为
Excel.Range
Type,然后依赖于内置属性Columns
),尽管我认为这可能更令人困惑。 Example: if you have as input range C1:H5, "C:C" is the first column, "D:D" the second column, etc. With my approach, the first column will always be "A:A", the second column "B:B", etc. 示例:如果输入范围C1:H5,则“ C:C”为第一列,“ D:D”为第二列,依此类推。以我的方法,第一列将始终为“ A:A”,第二列“ B:B”,依此类推。
Example of iterating through columns in a given range ( inputRange
): 在给定范围(
inputRange
)中遍历列的示例:
foreach(Excel.Range curCol in inputRange.Columns)
{
if (curCol.Value2 != null)
{
//As far as each column only has one row, each column can be associated with a cell
string curVal = curCol.Value2.ToString();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.