简体   繁体   English

如何在 C# 中使用 Microsoft.Office.Interop.Excel 添加数据透视表过滤器

[英]How to add pivot table filters with Microsoft.Office.Interop.Excel in C#

I create a pivot table based on an Excel (.xlsx) file.我基于 Excel (.xlsx) 文件创建了一个数据透视表。 The program adds fields to rows, values, and the filter.该程序将字段添加到行、值和过滤器。 Using PivotFilters.Add2 causes 0x800a03ec error which terminates the program.使用 PivotFilters.Add2 会导致 0x800a03ec 错误,从而终止程序。 How to properly use PivotFilters.Add2 ?如何正确使用PivotFilters.Add2

I tried filtering on different fields with different data types.我尝试对具有不同数据类型的不同字段进行过滤。 Also, I tried using Type.Missing in a place of unused arguments.另外,我尝试在未使用参数的地方使用Type.Missing There seems to be plenty of information of this method for VB, but not so much for C#.对于 VB,这种方法的信息似乎很多,但对于 C# 却没有那么多。

Items selected in the filter should be between the two dates on the last line.在过滤器中选择的项目应该在最后一行的两个日期之间。

    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));
  #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();
            }
        }
    }

As mentioned above by Asger, the filter can't be added to a page field.正如 Asger 上面提到的,过滤器不能添加到页面字段。 Instead, the pivot item's visibility property has to be set.相反,必须设置数据透视项的可见性属性。

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;
    }
}

找到几乎所有互操作问题的答案的最佳方法是记录一个宏,然后检查源。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 C# microsoft.office.interop.excel 添加图表 - C# microsoft.office.interop.excel Add Chart COMException C#Microsoft.Office.Interop.Excel - COMException C# Microsoft.Office.Interop.Excel C#MergeArea错误Microsoft.office.interop.excel - C# MergeArea Error Microsoft.office.interop.excel C#命令行添加对Microsoft.Office.Interop.Excel的引用 - C# command line add reference to Microsoft.Office.Interop.Excel C# 使用 Microsoft.Office.Interop.Excel 添加新的 SERIES 与其他工作表的范围 - C# using Microsoft.Office.Interop.Excel Add new SERIES With range from other WorkSheet 如何在 C# 中使用 Microsoft.Office.Interop.Excel 在 Excel 中的矩形内写入文本 - How to write a text inside a rectangle in excel using Microsoft.Office.Interop.Excel in c# 如何在不使用 Microsoft.Office.Interop.Excel 库的情况下在 C# 中读取 excel 文件 - How to read an excel file in C# without using Microsoft.Office.Interop.Excel libraries 如何从C#(Microsoft.Office.Interop.Excel)中的数据透视表对象获取可见的PivotField对象 - How to get Visible PivotField Object from a PivotTable object in C#(Microsoft.Office.Interop.Excel) 如何将saveAs更改为下载文件[Microsoft.Office.Interop.Excel] C# - How to change saveAs to be Download file [Microsoft.Office.Interop.Excel] C# 如何使用C#Excel“Microsoft.Office.Interop.Excel”来计算一列中非空单元格的数量 - How can I use C# Excel “Microsoft.Office.Interop.Excel”, to count the amount of not empty cells in a one columns
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM