使用C#中的Office.Interop.Excel在Excel中获取特定列的筛选值

时间:2016-03-30 11:44:41

标签: c# excel interop office-interop

我有一张名为" mySheet"的Excel表格。有列:"姓名","性别","分部"。

我想得到一系列学生姓名,他们的分部是" D"。

以下是我的代码:

Excel.Sheets ExcelSheets = excelWorkBook.Sheets;
Excel.Worksheet excelWorkSheet = ExcelSheets.get_Item(1);
Excel.Range excelRange = excelWorkSheet.UsedRange;
excelRange.AutoFilter(3, "D", Excel.XlAutoFilterOperator.xlAnd, Type.Missing, Type.Missing);
Excel.Range firstColumn = excelRange.Columns[1];
System.Array myvalues = (System.Array)firstColumn.Cells.Value;
strarrCreateExcel = myvalues.OfType<object>().Select(o => o.ToString()).ToArray();
strarrCreateDB = strarrCreateExcel;

1 个答案:

答案 0 :(得分:0)

请尝试以下代码:

        private void AutoFilterNames()
    {
        xl.Application xlApp = new xl.Application();
        xl.Workbooks xlWbks = xlApp.Workbooks;
        xl.Workbook xlWbk = xlWbks.Open(@"C:\Temp\Book1.xlsx");

        xl.Sheets xlSheets = xlWbk.Sheets;
        xl.Worksheet xlWorkSheet = xlSheets.get_Item(1);
        xl.Range xlUsedRange = xlWorkSheet.UsedRange;
        xlUsedRange.AutoFilter(3, "D", xl.XlAutoFilterOperator.xlAnd, Type.Missing, Type.Missing);

        xl.Range filteredRange = xlUsedRange.SpecialCells(xl.XlCellType.xlCellTypeVisible);
        var names = new List<string>();

        for (int areaId = 2; areaId <= filteredRange.Areas.Count; areaId++)
        {
            xl.Range areaRange = filteredRange.Areas[areaId];
            object[,] areaValues = areaRange.Value;
            names.Add(areaValues[1, 1].ToString());
        }

        var namesToArray = names.ToArray();
    }

注意:不要忘记发布excel对象。您可以从here

获得帮助