【问题标题】:C#. Excel. Need to programmatically reapply a filter on a spreadsheet opened in a console appC#。 Excel。需要以编程方式在控制台应用程序中打开的电子表格上重新应用过滤器
【发布时间】:2017-12-12 23:21:29
【问题描述】:

我有一个使用 Microsoft.Office.Interop.Excel 参考的 C# 控制台应用程序。该应用程序打开一个 Excel 电子表格,对其进行写入,保护工作表,保存它,然后关闭 Excel。这一切都有效。

电子表格在一张工作表的一部分上有一个过滤器。我需要应用程序在我写入数据后自动重新应用过滤器。

我尝试使用Worksheets.AutoFilter.ApplyFilter()。这会导致

未处理的异常

...但是它确实以某种形式工作。

// The two lines of code below cause the unhandled exception 
// in a console app but not in a form app.
// Refresh the filter programmatically
Excel.Worksheet ceSheet = Globals.xlApp.Worksheets["FAW Summary"];
ceSheet.AutoFilter.ApplyFilter();

我还尝试使用 SendKeys.SendApplicationContext 类发送 Ctrl-Alt-L 组合键重新申请。这不会给我一个错误,但在控制台应用程序中运行时它也不会做任何事情。

// Refresh the filter with SendKeys
if (!Globals.interactiveMode) Application.Run(new AGMDataExtractConsoleContext());

AGMDataExtractConsoleContextApplicationContext 类型的类。它应该从控制台运行应用程序,然后使用SendKeys.Send 传递击键。

标签: c# excel console autofilter


【解决方案1】:

根据 MSDN 文档,Worksheets 接口没有 AutoFilter 属性。您需要遍历Workbook 中的所有Worksheets 并调用ApplyFilter。 请注意,如果工作表中不存在过滤器,AutoFilter 将具有 null 值。

我为此创建了一个简单的扩展:

public static class WorksheetExtensions
{
    public static void ReapplyFilters(this Sheets sheets)
    {
        if (sheets == null) return;

        var c = sheets.Count;
        for (var i = 1; i <= c; i++)
        {
            try
            {
                var sh = sheets[i];
                if (sh.AutoFilter != null)
                    sh.AutoFilter.ApplyFilter();
            }
            catch (Exception e)
            {
                // some log
            }
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多