为什么最后一行永远不会被读取?

你好,我有一个问题,为什么最后一行永远不会被读取? 不pipe它在excel文件中只有一行还是100行都不重要。 最后一行从不显示在列表中。 而我不知道为什么….

这是我的Excel文件: Excel文件

这是我的方法:

public List<string> getListData(bool skipFirstRow, int numberOfColumns, string filepath) { int startpoint = 1; int cell = 1; int row = 1; List<string> stringList = new List<string>(); //Open Excel (Application) var excelApplication = openExcelApplication(); //Open Excel File Excel.Workbook excelWorkbook = excelApplication.Workbooks.Open(filepath); //Get the Worksheets from the file Excel.Sheets excelSheets = excelWorkbook.Worksheets; //Select the first Worksheet Excel.Worksheet worksheet = (Excel.Worksheet)excelSheets.get_Item(1); if (skipFirstRow == true) { startpoint = 2; } Excel.Range range = worksheet.get_Range("A" + Convert.ToString(startpoint), Missing.Value); while ((range.Cells[startpoint, cell] as Excel.Range).Value2 != null) { for (int i = 1; i <= numberOfColumns + 1; i++) { string sValue = (range.Cells[row, cell] as Excel.Range).Value2.ToString(); stringList.Add(sValue); cell++; } startpoint++; cell = 1; row++; } closeExcelApplication(excelApplication); var result = stringList .Select((item, index) => new { Item = item, Index = index }) .GroupBy(x => x.Index / numberOfColumns) .Select(g => string.Join(";", g.Select(x => x.Item))) .ToList(); return result; } 

我试着用debugging器,甚至谷歌。 然后我尝试了最后使用的行的东西,但没有工作。

 Excel.Range last = worksheet.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell, Type.Missing); Excel.Range range = worksheet.get_Range("A1", last); int lastUsedRow = last.Row; int lastUsedColumn = last.Column; 

任何帮助或build议将是伟大的,谢谢你的时间和帮助。

你的algorithm是越野车。

让我们来看看skipFirstRow为true并且Excel工作表有三行1,2和3时会发生什么。在while循环的开始,我们有以下情况:

 startpoint = 2 row = 1 

在第一次迭代期间,while循环读取第1行的内容。迭代之后,我们有以下情况:

 startpoint = 3 row = 2 

在第二次迭代期间,while循环读取第2行的内容。迭代之后,我们有以下情况:

 startpoint = 4 row = 3 

由于range.Cells[startpoint, cell]是空的,所以你的代码停在这里。 行1和行2已被读取,行3已被忽略。

正如你所看到的,你的问题的原因是你在startpoint 检查行并读取行中的row ,当这两个不同时,你有一个问题。 build议的解决scheme:删除startpointvariables并使用row

Excel表格显示第一行数字为1,但内部从0开始,可能是读取所有数据,将不同的testing数据放在最后一列