c# - Excel Interop 只读过滤行

标签 c# excel office-interop excel-interop

原始未过滤表

Original non filtered table

过滤表

enter image description here

我正在尝试使用 Interop.Excel 读取 .xlsx 文件。 xlRange 变量似乎有一个奇怪的行为,当我将它设置为仅显示过滤后的单元格(可见)时:

Excel.Range xlRange = xlWorksheet.UsedRange.SpecialCells(Excel.XlCellType.xlCellTypeVisible, Type.Missing);

调试:

当表没有被过滤时:

xlRange.Count: 15//表格中的元素总数

rowCount: 5//这包括标题

过滤表格时:

xlRange.Count: 9//这是正确的

rowCount: 1//这里应该是3(包括header)

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

最佳答案

我怀疑您想要的是迭代 .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();
}

当您指定范围内的行、列时,我怀疑它会转到该行(相对于范围)。

试一试,然后告诉我。

关于c# - Excel Interop 只读过滤行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54479899/

相关文章:

.net - 使用 Office Interop 通过虚拟目录运行时出错

c# - 如何将 xml 架构/设计文件添加到 Excel Interop?

c# - 从 .Net Core 控制台应用程序更新 Firebase Firestore 中的文档

c# - 如何在插入前更新 LINQ 类

c# - 使用 C# 解析 XLS 文件时出现问题

VBA - 无法从 For 循环内的 If 语句返回值

c# - 浮点运算 - Double 类型的模运算符

c# - 如何让 VS2010 使用 3.0 C# 编译器而不是 4.0?

c# - 为什么在使用 OleDb 导入 Excel 时忽略第一个空行

vb.net - Outlook.Application 未定义