你好,我有一个问题,为什么最后一行永远不会被读取? Excel 文件中只有一行还是 100 行都没关系。最后一行永远不会出现在列表中。我不知道为什么......
这是我的方法:
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;
}
我用调试器甚至谷歌尝试过。然后我尝试了最后使用的行内容,但没有成功。
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;
任何帮助或建议都会很棒,感谢您的时间和帮助。
最佳答案
你的算法有问题。
让我们看看当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
,当这两者不同时,就会遇到问题。建议的解决方案:删除 startpoint
变量并使用 row
代替。
关于c# - 为什么最后一行永远不会被读取?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37431051/