C# 如何在C中使用Microsoft.Office.Interop.Excel添加透视表筛选器#

C# 如何在C中使用Microsoft.Office.Interop.Excel添加透视表筛选器#,c#,excel,pivot-table,excel-interop,C#,Excel,Pivot Table,Excel Interop,我基于Excel(.xlsx)文件创建了一个透视表。程序将字段添加到行、值和筛选器中。使用PivotFilters.Add2会导致0x800a03ec错误,从而终止程序。如何正确使用数据透视过滤器.Add2 我试着用不同的数据类型过滤不同的字段。此外,我还尝试在未使用参数的位置使用Type.Missing。对于VB来说,似乎有很多关于这种方法的信息,但是对于C#来说,就没有那么多了 筛选中选择的项目应介于最后一行的两个日期之间 var xlApp = new Microsoft.Offi

我基于Excel(.xlsx)文件创建了一个透视表。程序将字段添加到行、值和筛选器中。使用PivotFilters.Add2会导致0x800a03ec错误,从而终止程序。如何正确使用
数据透视过滤器.Add2

我试着用不同的数据类型过滤不同的字段。此外,我还尝试在未使用参数的位置使用
Type.Missing
。对于VB来说,似乎有很多关于这种方法的信息,但是对于C#来说,就没有那么多了

筛选中选择的项目应介于最后一行的两个日期之间

    var xlApp = new Microsoft.Office.Interop.Excel.Application();
    xlApp.Visible = true;
    var workBook = xlApp.Workbooks.Open(spreadsheetLocation);
    var workSheet1 = (Microsoft.Office.Interop.Excel.Worksheet)workBook.Sheets["Data"];
    var workSheet2 = (Microsoft.Office.Interop.Excel.Worksheet)workBook.Sheets.Add();

    Microsoft.Office.Interop.Excel.Range last = workSheet1.Cells.SpecialCells(Microsoft.Office.Interop.Excel.XlCellType.xlCellTypeLastCell, Type.Missing);
    Microsoft.Office.Interop.Excel.Range range = workSheet1.get_Range("A1", last);

    Microsoft.Office.Interop.Excel.PivotCaches pivotCaches = null;
    Microsoft.Office.Interop.Excel.PivotCache pivotCache = null;
    Microsoft.Office.Interop.Excel.PivotTable pivotTable = null;
    Microsoft.Office.Interop.Excel.PivotFields pivotFields = null;
    Microsoft.Office.Interop.Excel.PivotField filterField = null;
    Microsoft.Office.Interop.Excel.PivotField accNumField = null;
    Microsoft.Office.Interop.Excel.PivotField amountPaidField = null;

    pivotCaches = workBook.PivotCaches();
    pivotCache = pivotCaches.Create(XlPivotTableSourceType.xlDatabase, range);

    pivotTable = pivotCache.CreatePivotTable(workSheet2.Cells[1,1]);
    pivotFields = (Microsoft.Office.Interop.Excel.PivotFields)pivotTable.PivotFields();
    amountPaidField = (Microsoft.Office.Interop.Excel.PivotField)pivotFields.Item("AmountPaid");
    amountPaidField.Orientation = Microsoft.Office.Interop.Excel.XlPivotFieldOrientation.xlDataField;
    amountPaidField.NumberFormat = "$#,###,###.00";

    accNumField = (Microsoft.Office.Interop.Excel.PivotField)pivotFields.Item("AccNumber");
    accNumField.Orientation = Microsoft.Office.Interop.Excel.XlPivotFieldOrientation.xlRowField;

    filterField = (Microsoft.Office.Interop.Excel.PivotField)pivotFields.Item("AccDate");
    filterField.Orientation = Microsoft.Office.Interop.Excel.XlPivotFieldOrientation.xlPageField;
    filterField.EnableMultiplePageItems = true;
    filterField.PivotFilters.Add2(XlPivotFilterType.xlDateBetween, Type.Missing, DateTime.Now.AddDays(-30), DateTime.Now.AddDays(-20));

正如Asger前面提到的,过滤器不能添加到页面字段。相反,必须设置轴项目的可见性属性

var pivotItems = filterField.PivotItems();
DateTime date = Convert.ToDateTime(item.Name);
foreach (var item in pivotItems)
{
    item.Visible = false;
    if (date < DateTime.Now.AddDays(-30) || date > DateTime.Now.AddDays(-20))
    {
        item.Visible = true;
    }
}
var pivotItems=filterField.pivotItems();
DateTime日期=Convert.ToDateTime(item.Name);
foreach(数据透视项中的变量项)
{
可见项=假;
if(dateDateTime.Now.AddDays(-20))
{
item.Visible=true;
}
}
#首先删除两行,然后创建一个数据透视表#
使用制度;
使用System.Collections.Generic;
使用System.Linq;
使用系统文本;
使用System.Threading.Tasks;
使用Microsoft.Office.Interop.Excel;
命名空间控制台应用程序4
{
班级计划
{
公共静态字符串列(int列)
{
列--;
如果(列>=0&&column<26)
返回((char)('A'+列)).ToString();
否则,如果(列>25)
返回列(列/26)+列(列%26+1);
其他的
抛出新异常(“无效列#“+(列+1).ToString());
}
静态void Main(字符串[]参数)
{
尝试
{
字符串路径=@“C:\Users\UX155512\Documents\Book1fd.xlsx”;
var excelFile=新应用程序();
工作簿=excelFile.Workbooks.Open(路径);
工作表=工作簿。工作表[1];
工作表数据透视表=工作簿.Worksheets.Add(
System.Reflection.Missing.Value,
工作簿.工作表[工作簿.工作表.计数],
1.
制度、反思、缺失、价值);
最后一个范围=工作表.Cells.SpecialCells(XlCellType.xlCellTypeLastCell,Type.Missing);
int lastRow=last.Row;
int lastCol=last.Column;
字符串lastColVal=列(lastCol);
字符串lastFilledCol=lastColVal+lastRow.ToString();
Console.WriteLine(lastFilledCol);
控制台写入线(lastColVal);
Console.WriteLine(最后一行);
控制台写入线(lastCol);

对于(int i=1;i),如果手动尝试,您将看到无法向页面字段(仅对行或列字段)添加筛选器。因此,您必须循环其数据透视项并设置其可见性。并且您必须确保至少有一个数据透视项保持可见(如果尝试将其全部设置为不可见,则会出现错误)。回答得很好,但请记住:至少有一个数据透视项必须保持可见(您不能禁用页面字段的所有数据透视项)。最坏的情况是:如果只有循环的最后一个数据透视项满足条件,则直接在…之前将其设置为
visible=false
,并出现错误。
  #First it deletes two rows and then it creates a pivot table#
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using Microsoft.Office.Interop.Excel;
    
    
    namespace ConsoleApplication4
    {
        class Program
        {
            public static string Column(int column)
            {
                column--;
                if (column >= 0 && column < 26)
                    return ((char)('A' + column)).ToString();
                else if (column > 25)
                    return Column(column / 26) + Column(column % 26 + 1);
                else
                    throw new Exception("Invalid Column #" + (column + 1).ToString());
            }
    
            static void Main(string[] args)
    
            {
               
    
                try
                {
                    string path = @"C:\Users\UX155512\Documents\Book1fd.xlsx";
                    var excelFile = new Application();
                    Workbook workBook = excelFile.Workbooks.Open(path);
                    Worksheet workSheet = workBook.Worksheets[1];
                    Worksheet pivotSheet = workBook.Worksheets.Add(
                        System.Reflection.Missing.Value,
                        workBook.Worksheets[workBook.Worksheets.Count],
                        1,
                        System.Reflection.Missing.Value);
    
    
    
    
                    Range last = workSheet.Cells.SpecialCells(XlCellType.xlCellTypeLastCell, Type.Missing);
                    int lastRow = last.Row;
                    int lastCol = last.Column;
                    string lastColVal = Column(lastCol);
                    string lastFilledCol = lastColVal + lastRow.ToString();
                    Console.WriteLine(lastFilledCol);
                    Console.WriteLine(lastColVal);
                  
                    Console.WriteLine(lastRow);
                    Console.WriteLine(lastCol);
    
                   
                    for (int i = 1; i <= lastRow; i++)
                    {
                        if (workSheet.Cells[1][i].Value == ("HDR"))
                        {
                            workSheet.Rows[i].Delete();
                            Console.WriteLine("The Row Containing HDR has been deleted");
                        }
                        if (workSheet.Cells[1][i].Value == ("TRL"))
                        {
                            workSheet.Rows[i].Delete();
                            Console.WriteLine("The Row Containing TLR has been deleted");
                        }
    
                    }
    
    
                   
                    Range lastRange = workSheet.Range["A1", lastFilledCol];
    
                    
    
                    
                    pivotSheet.Name = "Pivot Table";
                   
                    Range range = pivotSheet.Cells[1, 1];
                    PivotCache pivotCache = (PivotCache)workBook.PivotCaches().Add(XlPivotTableSourceType.xlDatabase, lastRange);
                    PivotTable pivotTable = (PivotTable)pivotSheet.PivotTables().Add(PivotCache: pivotCache, TableDestination: range);
                    PivotField pivotField = (PivotField)pivotTable.PivotFields("Plan Number");
                    pivotField.Orientation = XlPivotFieldOrientation.xlRowField;
    
                    PivotField pivotField2 = (PivotField)pivotTable.PivotFields("Source");
                    pivotField2.Orientation = XlPivotFieldOrientation.xlColumnField;
    
                    PivotField pivotField3 = (PivotField)pivotTable.PivotFields("Total");
                    pivotField3.Orientation = XlPivotFieldOrientation.xlDataField;
                    pivotField3.Function = XlConsolidationFunction.xlSum;
                   
    
                 
                    workBook.SaveAs(@"C:\Users\UX155512\Documents\Excel Dump\Trial9.xlsx");
                    workBook.Close();
                    
    
                   
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                   
                }
    
                Console.Read();
            }
        }
    }