如何使用C#冻结顶行并在Excel Automation中应用过滤器

KBP*_*KBP 42 c# excel vba export-to-excel office-interop

我有自动化从C#创建Excel文档.我试图冻结我的工作表的顶行并应用过滤器.如果选择"视图">"冻结窗格">"冻结顶行",然后选择顶行"数据">"筛选",则与Excel 2010中的相同.我不知道如何应用过滤器,但以下是我尝试冻结顶行,它只是冻结整个工作表.有没有人能解决我的问题.数据过滤问题是我需要更多帮助的地方,所以如果有人有解决方案,请赐教.

非常感谢KBP

        workSheet.Activate();
        Excel.Range firstRow = (Excel.Range)workSheet.Rows[1];
        firstRow.Activate();
        firstRow.Select();
        firstRow.Application.ActiveWindow.FreezePanes = true;
Run Code Online (Sandbox Code Playgroud)

KBP*_*KBP 64

我想到了!

@ Jaime解冻顶行的解决方案完美无缺.以下是我应用过滤器的解决方案:

谢谢,KBP

// Fix first row
workSheet.Activate();
workSheet.Application.ActiveWindow.SplitRow = 1;
workSheet.Application.ActiveWindow.FreezePanes = true;
// Now apply autofilter
Excel.Range firstRow = (Excel.Range)workSheet.Rows[1];
firstRow.AutoFilter(1, 
                    Type.Missing, 
                    Excel.XlAutoFilterOperator.xlAnd, 
                    Type.Missing, 
                    true);
Run Code Online (Sandbox Code Playgroud)

  • @KBP:为什么不删除冗余代码呢? (2认同)

Jai*_*Oro 32

试试这个...

workSheet.Activate();
workSheet.Application.ActiveWindow.SplitRow = 1;
workSheet.Application.ActiveWindow.FreezePanes = true;
Run Code Online (Sandbox Code Playgroud)


Koe*_*oen 6

workSheet.EnableAutoFilter = true; 
workSheet.Cells.AutoFilter(1); 

//Set the header-row bold
workSheet.Range["A1", "A1"].EntireRow.Font.Bold = true;  

//Adjust all columns
workSheet.Columns.AutoFit(); 
Run Code Online (Sandbox Code Playgroud)

可能有一些System.Reflection.Missing.Value需要与参数一起传递,但这是我已经转换出来的VB.Net代码.