如何跳过使用c#在Excel中跨越多行的单元格

所以我有一个循环,就像这样..:

for (int i = 12; i < 200; i++) { //Console.WriteLine(Convert.ToString(sheet01.Cells[12, 2].Value2)); if (!(string.IsNullOrEmpty(sheet01.Cells[i, 2].Value2)) && sheet01.Cells[i, 2].Value2.Length == 4) { Console.WriteLine(sheet01.Name); hcnNumber.Add(Convert.ToString(sheet01.Cells[i, 2].Value2)); } } 

此代码遇到一个错误,无论何时单元格[我,2]当我跨越多个列。

如何跳过跨越多列的行?

所以如果row.length> 1

谢谢

我试图在本地系统上处理您的需求。 如果我理解你的要求,你只需要显示那些只有第一列有值的行。如果例如一行有10列,其中全部或多于一列包含数据,则需要跳过。 我认为它应该可以帮助你达到目标。 下面是循环的代码,并给你预期的结果。

 Excel.Application xlApp = new Excel.Application(); Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(@"C:\Users\acn\Desktop\CopyofFinancialSample.xlsx"); Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1]; Excel.Range xlRange = xlWorksheet.UsedRange; int rowCount = xlRange.Rows.Count; int colCount = xlRange.Columns.Count; for (int i = 1; i <= rowCount; i++) { int count = 0; for (int j = 1; j <= colCount; j++) { //add useful things here! if (j != 1) { if (xlRange.Cells[i, j] != null && xlRange.Cells[i, j].Value2 != null) { count++; } } } if (count > 0) { } else { if (xlRange.Cells[i, 1] != null && xlRange.Cells[i, 1].Value2 != null) Console.WriteLine(xlRange.Cells[i, 1].Value2.ToString() + "\t"); } } 

如果您需要完整的控制台程序来testing请求,请在下面find

 class Program { static void Main(string[] args) { //Create COM Objects. Create a COM object for everything that is referenced Excel.Application xlApp = new Excel.Application(); Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(@"C:\Users\acn\Desktop\CopyofFinancialSample.xlsx"); Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1]; Excel.Range xlRange = xlWorksheet.UsedRange; int rowCount = xlRange.Rows.Count; int colCount = xlRange.Columns.Count; for (int i = 1; i <= rowCount; i++) { int count = 0; for (int j = 1; j <= colCount; j++) { //add useful things here! if (j != 1) { if (xlRange.Cells[i, j] != null && xlRange.Cells[i, j].Value2 != null) { count++; } } } if (count > 0) { } else { if (xlRange.Cells[i, 1] != null && xlRange.Cells[i, 1].Value2 != null) Console.WriteLine(xlRange.Cells[i, 1].Value2.ToString() + "\t"); } } //cleanup GC.Collect(); GC.WaitForPendingFinalizers(); //rule of thumb for releasing com objects: // never use two dots, all COM objects must be referenced and released individually // ex: [somthing].[something].[something] is bad //release com objects to fully kill excel process from running in the background Marshal.ReleaseComObject(xlRange); Marshal.ReleaseComObject(xlWorksheet); //close and release xlWorkbook.Close(); Marshal.ReleaseComObject(xlWorkbook); //quit and release xlApp.Quit(); Marshal.ReleaseComObject(xlApp); Console.ReadLine(); } } }