获取给定工作表中的最后Excel行有很多nice answers here。 但是,有时我们所需的只是给定列的最后一行,而不是整个电子表格。
我想到了一个解决方案,它似乎有点慢:
这是实现:
namespace ExcelTest
{
using System;
using Excel = Microsoft.Office.Interop.Excel;
public class Startup
{
const string filePath = @"C:\Users\gropc\Desktop\Sample.xlsx";
static void Main()
{
Excel.Application excel = new Excel.Application { Visible = true, EnableAnimations = false };
Excel.Workbook wkb = Open(excel, filePath);
foreach (Excel.Worksheet wks in wkb.Worksheets)
{
int lastRowA = LastRowPerColumn(1, wks);
int lastRowB = LastRowPerColumn(2, wks);
int lastRowC = LastRowPerColumn(3, wks);
Console.WriteLine($"{lastRowA} - {lastRowB} - {lastRowC}");
}
wkb.Close(true);
excel.Quit();
}
static int LastRowPerColumn(int column, Excel.Worksheet wks)
{
int lastRow = LastRowTotal(wks);
while (((wks.Cells[lastRow, column]).Text == "") && (lastRow != 1))
{
lastRow--;
}
return lastRow;
}
static int LastRowTotal(Excel.Worksheet wks)
{
Excel.Range lastCell = wks.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell, Type.Missing);
return lastCell.Row;
}
static Excel.Workbook Open(Excel.Application excelInstance,
string fileName, bool readOnly = false,
bool editable = true, bool updateLinks = true)
{
return excelInstance.Workbooks.Open(fileName, updateLinks, readOnly);
}
}
}
依赖项:
using Excel = Microsoft.Office.Interop.Excel
; const string filePath = @"C:\Users\gropc\Desktop\Sample.xlsx";
问题:
有什么想法可以避免循环吗?在vba中,该解决方案在1行中非常吸引人:
lastRow = ws.Cells(ws.Rows.Count, columnToCheck).End(xlUp).Row
与C#Excel Interop类似吗?