C#,打开excel文件并应用过滤器来检索特定的行?

时间:2017-07-16 13:54:49

标签: c# excel autofilter

问题: 我的代码总是返回一行而不是13行。

代码:

mylist1 <- 
list(c("yes", "no"), c("no", "other", "up", "down"), c("no", 
"yes", "maybe"), c("no", "yes", "maybe"), c("no", "yes", "maybe"
), c("no", "yes", "maybe"), c("no", "yes", "maybe"))

mylist2 <-
list(c("yes", "no"), c("no", "other", "up", "down"), c("no", 
"yes"), c("no", "yes"), c("no", "yes", "maybe"), c("no", "yes", 
"maybe"), c("no", "yes", "maybe"))

如您所见,我想要使用值“4”过滤第5列。它应该返回13行但它总是返回1行。

任何帮助将不胜感激

4 个答案:

答案 0 :(得分:1)

如果你使用 xlApp.Visible = true; 您可以使Excel应用程序可见

我刚刚运行了您的代码,它似乎与我的样本表一样正常工作

我的样本表

enter image description here

运行代码后,我看到过滤器正确应用

enter image description here

enter image description here

由于你得到1行,所以过滤器似乎不匹配任何行,行数为1可能只是标题行。

很少需要注意的事项是:

(1)第5列是E栏(不是F栏),即A栏是第1栏

(2)通过手动添加过滤器来交叉检查您的数据

答案 1 :(得分:0)

我回答我自己的问题:

...
...
Excel.Range filteredRange = xlrange.SpecialCells(Excel.XlCellType.xlCellTypeVisible,    Excel.XlSpecialCellsValue.xlTextValues);

for (int areaId = 1; areaId <= filteredRange.Areas.Count; areaId++)
{
    areaRange = filteredRange.Areas[areaId];
    object[,] areaValues = areaRange.Value;
    for (int row = 0; row < areaValues.GetLength(0); row++)
    {
        // ignore the Header row
        if (areaValues[row + 1, 1].ToString().ToLower() == "id") continue;

        //Add The Row To A List Or Array

     }
}

答案 2 :(得分:0)

set autoFilterCells.AutoFilter = true;

 using (ExcelRange autoFilterCells = ws.Cells[
    startRowIndex, territoryNameIndex,
    toRowIndex, totalIndex])
{
    autoFilterCells.AutoFilter = true;
}

答案 3 :(得分:0)

您只需要执行以下操作,我就对其进行了测试。

Excel.Range filteredRange = xlrange.SpecialCells(Excel.XlCellType.xlCellTypeVisible, Excel.XlSpecialCellsValue.xlTextValues);

int areaId; 
int filteredRow;
areaId = filteredRange.Areas.Count;
filteredRow = areaId - 1; //Skipping the header row
MessageBox.Show(filteredRow.ToString());