如何以编程方式为 XtraPivotGrid (Devexpress) select 数据源

How to select data source programmatically for XtraPivotGrid (Devexpress)

首先,我创建了一个包含 2 列和 20 行的 excel 文件。我把它变成了 table。我在 Visual Studio:

中试过这段代码
ExcelDataSource myExcelSource = new ExcelDataSource();
        myExcelSource.FileName = @"C:\Users\Fardin\Desktop\Book1.xlsx";
        ExcelWorksheetSettings worksheetSettings = new ExcelWorksheetSettings("Sheet1", "A1:B20");
        myExcelSource.SourceOptions = new ExcelSourceOptions(worksheetSettings);
        myExcelSource.SourceOptions.SkipEmptyRows = false;
        myExcelSource.SourceOptions.UseFirstRowAsHeader = true;
        myExcelSource.Fill();
        pivotGridControl1.DataSource = myExcelSource;

但是,我在最后一行遇到了运行时错误。它说:

System.NullReferenceException: 'Object reference not set to an instance of an object.'

如果 pivotGridControl1 为 null,则表示您在 windows 表单中缺少此 DevExpress 控件实例(我假设您使用的是 WinForms)。将 DevExpress PivotGridControl 拖放到您的表单上,并确保您输入了正确的控件 Name/Id.

试着仔细看看这两篇文章。:

绑定到 Excel 数据源

https://docs.devexpress.com/WindowsForms/115529/common-features/data-binding/binding-to-excel-data-sources

如何:创建字段并将 PivotGridControl 绑定到 Excel 数据源 https://docs.devexpress.com/WindowsForms/1921/controls-and-libraries/pivot-grid/examples/providing-data/how-to-bind-a-pivotgridcontrol-to-a-database