Форматирование сводной таблицы
Внешний вид сводной таблицы
Как создать сводную таблицу объясняет, как создать простую сводную таблицу. В этой статье описано, как настроить внешний вид сводной таблицы, устанавливая различные свойства:
- Опции формата сводной таблицы
- Опции формата полей сводной таблицы
- Опции формата данных поля
Как установить параметры форматирования сводной таблицы
Класс PivotTable контролирует общую сводную таблицу и может быть отформатирован различными способами.
Как установить тип автоформата
Microsoft Excel предлагает ряд заранее заданных форматов отчетов. Aspose.Cells for Node.js via C++ также поддерживает эти параметры форматирования. Для доступа к ним:
- Установите PivotTable.setIsAutoFormat(value) в true.
- Назначьте опцию форматирования из перечисления PivotTableAutoFormatType.
const AsposeCells = require("aspose.cells.node"); | |
//For complete examples and data files, please go to https:# github.com/aspose-cells/Aspose.Cells-for-.NET | |
//The path to the documents directory. | |
var dataDir = RunExamples.GetDataDir("."); | |
//Load a template file | |
var workbook = new AsposeCells.Workbook(dataDir + "Book1.xls"); | |
var pivotindex = 0; | |
//Get the first worksheet | |
var worksheet = workbook.getWorksheets().get(0); | |
//Accessing the PivotTable | |
var pivotTable = worksheet.getPivotTables().get(pivotindex); | |
//Setting the PivotTable report is automatically formatted | |
pivotTable.setIsAutoFormat(true); | |
//Setting the PivotTable atuoformat type. | |
pivotTable.setAutoFormatType(AsposeCells.PivotTableAutoFormatType.Report5); | |
//Saving the Excel file | |
workbook.save(dataDir + "output.xls"); |
Как устанавливать параметры форматирования
Приведенный ниже пример кода показывает, как отформатировать сводную таблицу для отображения общих итогов для строк и столбцов, а также как установить порядок полей отчета. Он также показывает, как установить пользовательскую строку для пустых значений.
const AsposeCells = require("aspose.cells.node"); | |
//For complete examples and data files, please go to https:# github.com/aspose-cells/Aspose.Cells-for-.NET | |
//The path to the documents directory. | |
var dataDir = RunExamples.GetDataDir("."); | |
//Load a template file | |
var workbook = new AsposeCells.Workbook(dataDir + "Book1.xls"); | |
//Get the first worksheet | |
var worksheet = workbook.getWorksheets().get(0); | |
var pivotindex = 0; | |
//Accessing the PivotTable | |
var pivotTable = worksheet.getPivotTables().get(pivotindex); | |
//Setting the PivotTable report shows grand totals for rows. | |
pivotTable.setRowGrand(true); | |
//Setting the PivotTable report shows grand totals for columns. | |
pivotTable.setColumnGrand(true); | |
//Setting the PivotTable report displays a custom string in cells that contain null values. | |
pivotTable.setDisplayNullString(true); | |
pivotTable.setNullString("null"); | |
//Setting the PivotTable report's layout | |
pivotTable.setPageFieldOrder(AsposeCells.PrintOrderType.DownThenOver); | |
//Saving the Excel file | |
workbook.save(dataDir + "output.xls"); |
Форматирование внешнего вида вручную
Чтобы вручную форматировать отчет сводной таблицы, вместо использования предустановленных форматов отчетов, используйте методы PivotTable.formatAll(style) и PivotTable.format(row, column, style). Создайте объект стиля для желаемого форматирования, например:
const AsposeCells = require("aspose.cells.node"); | |
//For complete examples and data files, please go to https:# github.com/aspose-cells/Aspose.Cells-for-.NET | |
//The path to the documents directory. | |
var dataDir = RunExamples.GetDataDir(".") | |
//Load a template file | |
var workbook = new AsposeCells.Workbook(dataDir + "Book1.xls"); | |
//Get the first worksheet | |
var worksheet = workbook.getWorksheets().get(0); | |
var pivot = worksheet.getPivotTables().get(0); | |
pivot.setPivotTableStyleType(AsposeCells.PivotTableStyleType.PivotTableStyleDark1); | |
var style = workbook.createStyle(); | |
style.getFont().setName("Arial Black"); | |
style.setPattern(AsposeCells.BackgroundType.Solid); | |
style.setForegroundColor(AsposeCells.Color.Yellow); | |
pivot.formatAll(style); | |
//Saving the Excel file | |
workbook.save(dataDir + "output.xls"); |
Как установить параметры форматирования поля сводной таблицы
Класс PivotField представляет собой поле в сводной таблице и может быть отформатировано несколькими способами. Приведенный ниже образец кода показывает, как:
- Получить строковые поля.
- Настроить итоги.
- Настроить автосортировку.
- Настроить автоотображение.
Как установить формат полей строк/столбцов/страниц
const AsposeCells = require("aspose.cells.node"); | |
//For complete examples and data files, please go to https:# github.com/aspose-cells/Aspose.Cells-for-.NET | |
//The path to the documents directory. | |
var dataDir = RunExamples.GetDataDir("."); | |
//Load a template file | |
var workbook = new AsposeCells.Workbook(dataDir + "Book1.xls"); | |
//Get the first worksheet | |
var worksheet = workbook.getWorksheets().get(0); | |
var pivotindex = 0; | |
//Accessing the PivotTable | |
var pivotTable = worksheet.getPivotTables().get(pivotindex); | |
//Setting the PivotTable report shows grand totals for rows. | |
pivotTable.setRowGrand(true); | |
//Accessing the row fields. | |
var pivotFields = pivotTable.getRowFields(); | |
//Accessing the first row field in the row fields. | |
var pivotField = pivotFields.get(0); | |
//Setting Subtotals. | |
pivotField.setSubtotals(AsposeCells.PivotFieldSubtotalType.Sum, true); | |
pivotField.setSubtotals(AsposeCells.PivotFieldSubtotalType.Count, true); | |
//Setting autosort options. | |
//Setting the field auto sort. | |
pivotField.setIsAutoSort(true); | |
//Setting the field auto sort ascend. | |
pivotField.setIsAscendSort(true); | |
//Setting the field auto sort using the field itself. | |
pivotField.setAutoSortField(-5); | |
//Setting autoShow options. | |
//Setting the field auto show. | |
pivotField.setIsAutoShow(true); | |
//Setting the field auto show ascend. | |
pivotField.setIsAscendShow(false); | |
//Setting the auto show using field(data field). | |
pivotField.setAutoShowField(0); | |
//Saving the Excel file | |
workbook.save(dataDir + "output.xls"); |
Как установить формат полей данных
Приведенный ниже образец кода показывает, как установить формат отображения и числовой формат для полей данных.
const AsposeCells = require("aspose.cells.node"); | |
//For complete examples and data files, please go to https:# github.com/aspose-cells/Aspose.Cells-for-.NET | |
//The path to the documents directory. | |
var dataDir = RunExamples.GetDataDir("."); | |
//Load a template file | |
var workbook = new AsposeCells.Workbook(dataDir + "Book1.xls"); | |
//Get the first worksheet | |
var worksheet = workbook.getWorksheets().get(0); | |
var pivotindex = 0; | |
//Accessing the PivotTable | |
var pivotTable = worksheet.getPivotTables().get(pivotindex); | |
//Accessing the data fields. | |
var pivotFields = pivotTable.getDataFields(); | |
//Accessing the first data field in the data fields. | |
var pivotField = pivotFields.get(0); | |
//Setting data display format | |
pivotField.showValuesAs(AsposeCells.PivotFieldDataDisplayFormat.PercentageOf, 1, AsposeCells.PivotItemPositionType.Next, 0); | |
//Setting number format | |
pivotField.setNumber(10); | |
//Saving the Excel file | |
workbook.save(dataDir + "output.xls"); |
Как очистить поля сводной таблицы
У класса PivotFieldCollection есть метод с именем clear(), который позволяет очистить поля сводной таблицы. Используйте его, когда вам нужно очистить все поля сводной таблицы в областях, например страница, столбец, строка или данные. Приведенный ниже образец кода показывает, как очистить все поля сводной таблицы в области данных.
const AsposeCells = require("aspose.cells.node"); | |
//For complete examples and data files, please go to https:# github.com/aspose-cells/Aspose.Cells-for-.NET | |
//The path to the documents directory. | |
var dataDir = RunExamples.GetDataDir(".") | |
//Load a template file | |
var workbook = new AsposeCells.Workbook(dataDir + "Book1.xls"); | |
//Get the first worksheet | |
var sheet = workbook.getWorksheets().get(0); | |
//Get the pivot tables in the sheet | |
var pivotTables = sheet.getPivotTables(); | |
//Get the first PivotTable | |
var pivotTable = pivotTables.get(0); | |
//Clear all the data fields | |
pivotTable.getDataFields().clear(); | |
//Add new data field | |
pivotTable.addFieldToArea(AsposeCells.PivotFieldType.Data, "Betrag Netto FW"); | |
//Set the refresh data flag on | |
pivotTable.setRefreshDataFlag(true); | |
//Refresh and calculate the pivot table data | |
pivotTable.refreshData(); | |
pivotTable.calculateData(); | |
pivotTable.setRefreshDataFlag(false); | |
//Saving the Excel file | |
workbook.save(dataDir + "output.xls"); |