如何使用 aspose-cells-python 24.10.0 将 row_fields 分组到一个单元格中

问题描述 投票:0回答:1

我在输入 Excel 文件中有 3 个非日期列,并且我想要 3 个可以显式分组的

PivotFieldType.ROW
字段,以便单元格上有一个选择字段下拉选项。此代码是通过 .Net 在 Python 的 aspose.cells 中编写的。

值应如何显示的屏幕截图。

format in which output should appear

python-3.x pivot-table aspose-cells dynamic-pivot
1个回答
0
投票

请参阅以下通过 .NET 使用 Aspose.Cells for Python 的示例代码供您参考。我已将列表(2 列)中的一些示例值动态插入到新创建的工作簿的工作表单元格中。请参考代码段,自行编写/更新自己的代码。

import pandas as pd
import numpy as np
import aspose.cells
from aspose.cells import Workbook, WorksheetCollection, Worksheet, CellsHelper, License
from aspose.cells.pivot import PivotFieldType, PivotTableAutoFormatType
from datetime import datetime

workbook = Workbook()
sheet = workbook.worksheets[0]

data = [
    ["Date", "Value"],
    [datetime(2024, 1, 1), 150],
    [datetime(2024, 1, 2), 200],
    [datetime(2024, 1, 3), 120],
    [datetime(2024, 2, 1), 180],
    [datetime(2024, 2, 2), 50]
]

# Populate the worksheet with data
for row_idx, row in enumerate(data):
    for col_idx, value in enumerate(row):
        sheet.cells.get(row_idx, col_idx).value = value

range = sheet.cells.create_range("A2:A6")
# Apply formatting to the range
style = workbook.create_style()
style.number = 14
range.set_style(style)

# Define the pivot table range (A1:B6)
pivot_table_range = f"A1:B{len(data)}"

# Add a pivot table to the worksheet at cell E5
pivot_index = sheet.pivot_tables.add(pivot_table_range, "E5", "PivotTable1")
pivot_table = sheet.pivot_tables[pivot_index]

# Add the "Date" field as a row field
pivot_table.add_field_to_area(PivotFieldType.ROW, 0)  # Date column
# Add the "Value" field as a data field (value field)
pivot_table.add_field_to_area(PivotFieldType.DATA, 1)  # Value column

# Get the PivotField for the Date (Row Field) and group by months
date_pivot_field = pivot_table.row_fields[0]
date_pivot_field.is_auto_sort = True 
date_pivot_field.is_auto_subtotals = True

# Group by Date (by month)
date_pivot_field.group_by(4.0, True)

# Add the "Date" field as row field after group to make it work
pivot_table.add_field_to_area(PivotFieldType.ROW, 0)  

# Enable filtering for the row field (Date)
pivot_table.row_fields[0].show_in_outline_form = True

# Set auto format style for the pivot table
pivot_table.auto_format_type = PivotTableAutoFormatType.REPORT6

# Refresh and calculate the pivot table data
pivot_table.refresh_data()
pivot_table.calculate_data()

# Save the workbook
workbook.save("e:\\test2\\out1_PivotTableGrouped1.xlsx")

希望,这有点帮助。

此外,您可以在专门的论坛中发布您的疑问。

PS。我在 Aspose 担任支持开发人员/布道者。

© www.soinside.com 2019 - 2024. All rights reserved.