透视表和源数据
Contents
[
Hide
]
透视表的源数据
有时您希望创建从不同数据源(如数据库)获取数据的透视表的Microsoft Excel报表,在设计时这些数据源是未知的。本文介绍了一种动态更改透视表数据源的方法。
更改透视表的数据源
- 创建一个新的设计模板。
-
创建一个新的设计模板文件,如下面的屏幕截图所示。
-
然后定义一个名为DataSource的命名范围,该范围引用这些单元格。
创建设计模板并定义命名范围,数据源
-
- 基于该命名范围创建数据透视表。
-
在Microsoft Excel中,选择数据,然后选择数据透视表和数据透视图报表。
-
根据第一步中创建的命名范围创建数据透视表。
基于命名范围创建数据透视表,数据源
-
- 将相应字段拖放到数据透视表的行和列中,然后按照下面的截图创建结果的数据透视表。
基于相应字段创建数据透视表
- 右键单击数据透视表,然后选择表选项。
-
在数据选项设置中选择打开时刷新。
设置数据透视表选项
-
现在,您可以将此文件保存为您的设计模板文件。
- 填充新数据并更改数据透视表的源数据。
- 一旦设计模板创建完成,使用以下代码修改数据透视表的源数据。
执行下面的示例代码会更改数据透视表的源数据。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from aspose.cells import Workbook | |
# The path to the documents directory. | |
dataDir = RunExamples.GetDataDir(".") | |
InputPath = dataDir + "Book1.xlsx" | |
# Creating a file stream containing the Excel file to be opened | |
fstream = open(InputPath, "rb") | |
# Opening the Excel file through the file stream | |
workbook = Workbook(fstream) | |
# Accessing the first worksheet in the Excel file | |
worksheet = workbook.worksheets[0] | |
# Populating new data to the worksheet cells | |
worksheet.cells.get("A9").put_value("Golf") | |
worksheet.cells.get("B9").put_value("Qtr4") | |
worksheet.cells.get("C9").put_value(7000) | |
# Changing named range "DataSource" | |
range = worksheet.cells.create_range(0, 0, 9, 3) | |
range.name = "DataSource" | |
# Saving the modified Excel file | |
workbook.save(dataDir + "output.xls") | |
# Closing the file stream to free all resources | |
fstream.close() |