原始未过滤表
已过滤表格
我正在尝试使用Interop.Excel读取.xlsx文件。将 xlRange 变量设置为仅显示已过滤的单元格(可见)时,它似乎具有奇怪的行为:
Excel.Range xlRange = xlWorksheet.UsedRange.SpecialCells(Excel.XlCellType.xlCellTypeVisible, Type.Missing);
调试:
未过滤表格时:
xlRange.Count:15 //表中元素总数
rowCount:5 //包括标题
过滤表格时:
xlRange.Count:9 //这是正确的
行数:1 //应为3(包括标题)
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(Directory.GetCurrentDirectory() + "\\Example.xlsx");
Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1];
Excel.Range xlRange = xlWorksheet.UsedRange.SpecialCells(Excel.XlCellType.xlCellTypeVisible, Type.Missing);
int rowCount = xlRange.Rows.Count;
int colCount = xlRange.Columns.Count;
//iterate over the rows and columns and print to the console as it appears in the file
//excel is not zero based!!
for (int i = 1; i <= rowCount; i++)
{
for (int j = 1; j <= colCount; j++)
{
//new line
if (j == 1)
Console.Write("\r\n");
//write the value to the console
if (xlRange.Cells[i, j] != null && xlRange.Cells[i, j].Value2 != null)
Console.Write(xlRange.Cells[i, j].Value2.ToString() + "\t");
}
}
请记住,xlRange.Count为9,我应该能够手动访问所有3行,而不管rowCount变量如何,但xlRange似乎是相同的原始未过滤范围:
Console.WriteLine(xlRange.Cells[1, 1]);//Writes ID, Correct
Console.WriteLine(xlRange.Cells[2, 1]);//Writes 1, Should be 2
Console.WriteLine(xlRange.Cells[3, 1]);//Writes 2, Should be 4
Console.WriteLine(xlRange.Cells[4, 1]);//Writes 3, Should not be able to acces this element element at all because xlRange.Count is 9
答案 0 :(得分:3)
我怀疑您想要的是迭代.Rows
属性,而不是按行/列的字面意思。像这样:
foreach (Excel.Range row in xlRange.Rows)
{
for (int j = 1; j <= colCount; j++)
{
//write the value to the console
if (row.Cells[1, j] != null && row.Cells[1, j].Value2 != null)
Console.Write(row.Cells[1, j].Value2.ToString() + "\t");
}
Console.WriteLine();
}
当您指定行,范围内的列时,我怀疑它会转到该确切的行(相对于范围)。
尝试一下,让我知道。