我想您的要求工作,我的本地系統上。如果我理解你的要求,你只需要顯示那些只有第一列有值的行,如果例如一行有10列,其中全部或多於1列包含數據,則需要跳過。我認爲它應該可以幫助你達到目標。 下面是循環並給出預期結果的代碼。
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");
}
}
如果你需要完整的控制檯程序來測試REQ,請在下面找到
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();
}
}
}
我找不到任何類似在線這個問題。我正在尋找一個if語句來檢測單元格數是否超過1行。 –