具有C#和Microsoft.Office.Interop.Excel的Excel中的数据透视表行为异常

问题描述

我正在关注Youtube教程,无法创建数据透视表。

到目前为止,我已经编写了以下代码来创建新的工作簿和工作表,并用示例数据填充它:

            string fileTest = "test.xlsx";
            if (File.Exists(fileTest))
                File.Delete(fileTest);

            Excel.Application app;
            Excel.Worksheet sheet;
            Excel.Workbook book;

            app = new Excel.Application();
            book = app.Workbooks.Add();
            sheet = (Excel.Worksheet)book.Worksheets.get_Item(1);

            sheet.Cells[1,1] = "Name";
            sheet.Cells[1,2] = "Salary";
            sheet.Cells[1,3] = "Hours";
            sheet.Cells[1,4] = "Friends";

            sheet.Cells[2,1] = "Frank";
            sheet.Cells[2,2] = 150000;
            sheet.Cells[2,3] = 40;
            sheet.Cells[2,4] = 2;

            sheet.Cells[3,1] = "Ann";
            sheet.Cells[3,2] = 300000;
            sheet.Cells[3,3] = 60;
            sheet.Cells[3,4] = 4;

在第一张纸上正确显示以下信息:

Original Table

然后,我尝试使用以下代码(紧随上述代码之后)创建数据透视表:


            Excel.Range range = sheet.Range["A1","D3"];

            Excel.Worksheet pivotSheet = (Excel.Worksheet)book.Worksheets.Add();

            pivotSheet.Name = "Pivot Table";

            Excel.Range range2 = pivotSheet.Cells[1,1];

            Excel.PivotCache pivotCache = (Excel.PivotCache)book.PivotCaches().Add(Excel.XlPivottableSourceType.xlDatabase,range);
            Excel.Pivottable pivottable = (Excel.Pivottable)pivotSheet.Pivottables().Add(PivotCache: pivotCache,TableDestination: range2,TableName: "Summary");

            Excel.PivotField pivotField = (Excel.PivotField)pivottable.PivotFields("Salary");
            pivotField.Orientation = Excel.XlPivotFieldOrientation.xldatafield;
            pivotField.Function = Excel.XlConsolidationFunction.xlSum;
            pivotField.Name = "Pay";

            Excel.PivotField pivotField2 = (Excel.PivotField)pivottable.PivotFields("Name");
            pivotField2.Orientation = Excel.XlPivotFieldOrientation.xlRowField;
            pivotField2.Name = "Coworkers";

            Excel.PivotField pivotField3 = (Excel.PivotField)pivottable.PivotFields("Hours");
            pivotField3.Orientation = Excel.XlPivotFieldOrientation.xldatafield;
            pivotField3.Function = Excel.XlConsolidationFunction.xlSum;
            pivotField3.Name = "Time";

            book.SaveAs(fileTest);
            book.Close();
            app.Quit();

希望创建一个这样的数据透视表,其中行按名称重命名为同事)分类,工资(重命名为工资)和小时(重命名时间)在底部总计:

Desired Table

但是,我的数据透视表却是这样的:

Resulting Table

我不确定我是否有编码错误,或者该库是否在较新版本的Excel中表现怪异。任何建议表示赞赏。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)