你好,我有一个问题,为什么最后一行永远不会被读取?不管它在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;
任何帮助或建议将是伟大的,所以感谢您的时间和帮助。
由于这是它现在它的工作原理。 – opelhatza