Code Reference

Here is the documentation of py-powerbi-report code.

There are two parts of power bi objects, one that works with the report (visuals and bookmarks) and another to work with the model (measures).

Power BI Report classes

PBIXFile

Module for class to work with core file of PBI

The layout of a Power BI report comes from a JSON file name Layout inside the .pbix file.

The class PBIXFile means capture the file and delivery it for PBIReport class to work with.

class pypbireport.pbi.pbifile.PBIXFile(pbix_path: str)

Class to work with PBIX File

This class represent a Power BI report file (extesion of .pbix). This class has two objectives:

  1. Extract the report layout JSON from a PBI report file.

  2. Save a new Power BI file with a report layout JSON.

Note

This isn’t prepare to work with PBIH files yet. The future plan is to manipulate report.json file directly.

Parameters:

pbix_path (str) – Path of a PBIX file.

pbix_path

Path of a PBIX file.

Type:

str

pbix

Zip file with PBIX files. PBIX file are composed by a collection of compressed files. pbix variable is an instantiation of the zip file.

Type:

zipfile.ZipFile

report_name

The name of report. Simple fil name without .pbix

Type:

str

extract_layout_and_encoding() str

Method to return the report layout JSON as a string

The Layout file is a JSON archive that contains all configuration of the Power BI report. This method reads the file and decodes it to a readable string for future serialization into a dict object.

Returns:

A string that represents the report layout JSON from Layout

file.

Return type:

str

extract_layout() None

Method to extract the Layout file from pbix and save in folder.

The Layout file is a JSON archive that contains all configuration of the Power BI report. This method simply extracts it from the PBIX zipped file and saves it in the working directory for consulting.

Returns:

None. Save a file with pattern layout_`report_name`.json in folder

save_report(layout_dict: str, replace_original: bool = False, suffix: str = 'ppr_out', file_name: str | None = None, open_file: bool = False) str

Method to save PBIX file hold as object of this class.

This method works in the following steps:
  1. Create a temp file.

  2. Passes all files inside PBIX zipped file for temp file, expect Report/Layout, SecurityBindings and Content_Types.xml.

  3. Inserts Report/Layout with layout_dict written in proper encoding, as well as inserts Content_Types.xml file

Note

SecurityBindings will be created after open PBIX file and save it.

Parameters:
  • layout_dict (str) – Layout dict (json) of a PBI report.

  • replace_original (bool, optional) – If is true, the original report will be replaced for a report with modification. Important: the original file should be closed. Defaults to False.

  • suffix (str, optional) – You might want a suffix to report create by module. Defaults to ‘ppr_out’.

  • file_name (str | None, optional) – Give desired name for new report. Defaults to None.

  • open_file (bool, optional) – Not implemented. Defaults to False.

Returns:

Confirmation that report was saved into folder

Return type:

str

PBIReport

Module for class to work with visualization in PBI

class pypbireport.pbi.pbireport.PBIReport(pbix_path: str)

Class to represent a Power BI report

Parameters:

pbix_path (str) – Path of the Power BI report file.

pbix_path

Path of the Power BI report file.

Type:

str

layout_pbi_dict

A python dict from report layout JSON

Type:

dict

layout_pbi_str

A string from report layout JSON

Type:

str

pages_list

List of dicts representing report pages

Type:

list

visuals

List of Visual objects of report

Type:

list

pages_visuals

A dict with the key as page name and the value as list of Visual objects of each page

Type:

dict

bookmark

List of Bookmark objects of the report

Type:

list

bookmark_groups

List of BookmarkGroup objects of the report

Type:

list

resume_report_pages()

This method return a dict with page information

Returns:

A dict with page position, display name and id.

Return type:

info_dict (dict)

resume_report_visuals(page_name: str = '') DataFrame

Method to return a dataframe of information of visuals in report

Parameters:

page_name (str) – The page name that desire retrieve visuals of.

Returns:

A dataframe with all report visuals

Return type:

pd.DataFrame

create_duplicate_page(page_to_duplicate: str, page_name: str = 'ppr copy') None

This method duplicates a page in report

Parameters:

page_name (str) – The page to duplicate.

insert_visual_in_page(page_name: str, visual: tuple | Visual)

Insert a visual in a page.

Parameters:
  • page_name (str) – The page name where the visual will be.

  • visual (tuple | Visual) – A tuple of __id__ and __dict__ from a visual created with this class.

insert_bookmark(ppr_bookmark: tuple | Bookmark | BookmarkGroup)

Insert a bookmark into report.

Insert a created bookmark. Different from others parameters in layout JSON of PBI, the bookmarks are placed at ‘config’ key at the end of JSON. It is a kind of overall configuration of report.

Parameters:
  • bookmark (tuple) – a tuple with (id, dict) of a bookmark create

  • class. (in) –

Returns:

None

save_changes()

Consolidate all changes made through classes methods in layout dict.

This should run before save_report() to report reflect changes.

save_report(replace_original: bool = False, suffix: str = 'ppr_out', file_name: str | None = None, open_file=False)

Consolidate the report layout_dict input in a new PBIX file

Parameters:
  • replace_original (bool, optional) – If is true, the original report will be replaced for a report with modification. The original file should be closed. Defaults to False.

  • suffix (str, optional) – You might want a suffix to reports create by module. Defaults to ‘ppr_out’.

  • file_name (str | None, optional) – Desired report file name. Defaults to None.

  • open_file (bool, optional) – Not implemented. Defaults to False.

PBIVisual

class pypbireport.pbi.pbivisual.Visual(visual_dict: dict, page_name: str | None = '', page_id: str | None = '')

Class to represent a visual of Power BI.

A Power BI visual is represented by a JSON or a dictionary in python. They are hold in visualContainers key of each page in report layout JSON. From visual dictionary, it is possible to set a bunch of proprities, such as vertical and horizontal positions, as well the measure field. The visual dictionary structure is based in some other dictionary represent by keys like config, query and dataTranforms. After serialization of visual dictionary, these came as strings and they should be processed before extract or modify any content.

Note

As a disclaimer, all the work done here is just a reverse engineering of what Power BI design results. It is totally normal erros occurs and some features being implemented by another way.

Parameters:
  • visual_dict (dict) – The dictionary that represent a Power BI visual

  • page_name (str | None, optional) – The page where the visual is placed. It can be None, for new visuals. Defaults to ‘’.

  • page_id (str | None, optional) – The heximadecimal id page value. Defaults to ‘’.

original_visual

The original JSON format before any tranformation of the visual.

Type:

dict

visual

The dictionary that represent the visual.

Type:

dict

page_name

The page name where the visual is placed.

Type:

str

page_id

The hexadecimal page value where the visual is placed.

Type:

str

config

Dictonary that represents config of the visual. Hold a great part of visual display configurations, such as position.

Type:

dict

query

Dictonary that represents query that are done of visual display data.

Type:

dict

dataTransforms

Dictonary with configuration of data tranformation of the visual.

Type:

dict

filters

Dictonary with filters applied to the visual.

Type:

dict

id

Hexadecimal value that represent the visual. It should be unique in a report.

Type:

str

horizontal

The x position of the visual in a page.

Type:

float

vertical

The y position of the visual in a page.

Type:

float

height

The height of the visual.

Type:

float

width

The width of the visual.

Type:

float

visual_type

The Power BI type of the visual.

Type:

str

tab_order

The layer order of the visual in a page.

Type:

str

dump_dicts() None

Method to update values in the visual dict.

The Power BI visual dictionary will be converted to a JSON object. Within the JSON, the bellow keys should be in string format. This method is called within PBIReport.save_report() and performs this action before saving a new Power BI file.

export_visual_dicts(file_name: str | None = None)

Method to export dict of visual as a JSON file.

This method is a convinent way to export and provide a view of visual dictionary. This divide in ‘original’ and ‘transformed’ dictionaries. The ‘origina’ may contains the visual dictionary as this came from Power BI. It is not garanteed after some tranformations. The ‘transformed’ is the result of the parsing of string to dictionary object inside this class.

Parameters:

file_name (str | None, optional) – The name of file. Defaults to None.

pbivisual.create_new_visual(page_name: str, page_id: str, custom_template: dict | None = None) Visual

Function to create a new visual from a existing or custom template.

Here some template are offered to be create for futher customization. There are four options: card, column chart, slicer (dropdown or list) and a bookmark navagitor. The return of this funtion is a Viusal object of chossen class that can be inserted inside a report.

Parameters:
  • visual ('str') – The desired visual.

  • page_name (str) – The page name where visual will be placed.

  • page_id (str) – The page hexadecimal value where visual will be placed.

  • custom_template (dict | None, optional) – A custom visual dictionary can be an input for the new visual. Defaults to None.

Returns:

A visual object choosen.

Return type:

Visual

pbivisual.copy_visual() Visual

Function to copy an existing visual of report.

Use this function when you want to get an existing visual in report and to copy it for futher modification. The return copied visual has no page allocated. Remember to insert it in a page after copy.

Parameters:

visual (Visual) – A visual object.

Returns:

A copied visual.

Return type:

Visual

Specific Visuals

Module for class to work with visuals of Power BI

class pypbireport.pbi.pbivisual.BaseVisual(visual_dict: dict, page_name, page_id)

Class to represent the base of any specific visual type

More than generic class Visual, some visuals have their specificity, namely the attributes. This class works to initiate this specific classes.

Parameters:
  • visual_dict (dict) – The dictionary that represent a Power BI visual

  • page_name (str | None, optional) – The page where the visual is placed. It can be None, for new visuals. Defaults to ‘’.

  • page_id (str | None, optional) – The heximadecimal id page value. Defaults to ‘’.

_obj_name

The name of viusal type

Type:

str

_attrs

A dictonary with set of attributes for the visual type

Type:

dict

_field_attrs

A dictonary with set of fields attributes for the visual type

Type:

dict

class pypbireport.pbi.pbivisual.Card(visual_dict: dict, page_name, page_id)

Representation of Power BI Card visual

Parameters:
  • visual_dict (dict) – The dictionary that represent a Power BI visual

  • page_name (str | None, optional) – The page where the visual is placed. It can be None, for new visuals. Defaults to ‘’.

  • page_id (str | None, optional) – The heximadecimal id page value. Defaults to ‘’.

__visual

Visual name key to use in main dictonary of attributes

Type:

str

_obj_name

Viusal name to use in __repr__. _attrs (dict): A dictonary with set of attributes for the visual type

Type:

str

_field_attrs

A dictonary with set of fields attributes for the visual type

Type:

dict

class pypbireport.pbi.pbivisual.Column(visual_dict: dict, page_name, page_id)

Representation of Power BI Column Chart visual

Parameters:
  • visual_dict (dict) – The dictionary that represent a Power BI visual

  • page_name (str | None, optional) – The page where the visual is placed. It can be None, for new visuals. Defaults to ‘’.

  • page_id (str | None, optional) – The heximadecimal id page value. Defaults to ‘’.

__visual

Visual name key to use in main dictonary of attributes

Type:

str

_obj_name

Viusal name to use in __repr__. _attrs (dict): A dictonary with set of attributes for the visual type

Type:

str

_field_attrs

A dictonary with set of fields attributes for the visual type

Type:

dict

class pypbireport.pbi.pbivisual.Slicer(visual_dict: dict, page_name, page_id)

Representation of Power BI Slicer visual

Parameters:
  • visual_dict (dict) – The dictionary that represent a Power BI visual

  • page_name (str | None, optional) – The page where the visual is placed. It can be None, for new visuals. Defaults to ‘’.

  • page_id (str | None, optional) – The heximadecimal id page value. Defaults to ‘’.

__visual

Visual name key to use in main dictonary of attributes

Type:

str

_obj_name

Viusal name to use in __repr__. _attrs (dict): A dictonary with set of attributes for the visual type

Type:

str

_field_attrs

A dictonary with set of fields attributes for the visual type

Type:

dict

class pypbireport.pbi.pbivisual.BookmarkSlicer(visual_dict: dict, page_name, page_id)

Representation of Power BI Bookmark Navigator visual

Parameters:
  • visual_dict (dict) – The dictionary that represent a Power BI visual

  • page_name (str | None, optional) – The page where the visual is placed. It can be None, for new visuals. Defaults to ‘’.

  • page_id (str | None, optional) – The heximadecimal id page value. Defaults to ‘’.

__visual

Visual name key to use in main dictonary of attributes

Type:

str

_obj_name

Viusal name to use in __repr__. _attrs (dict): A dictonary with set of attributes for the visual type

Type:

str

_field_attrs

A dictonary with set of fields attributes for the visual type

Type:

dict

Power BI Model classes

Module to work with Power BI Model

class pypbireport.pbi.pbimodel.PBIModel(pbix_path: str)

Class to represent Power BI Analysis Services tabular model

This class only works with opened model in memory. It is because the Power BI Analysis Services model is launched when the pbix file is opened. Data model inside zipped file is compressed.

Parameters:

pbix_path (str) – Path of an opened Power BI file.

pbix_path

Path of the Power BI file.

Type:

str

report_name

The name of Power BI report file.

Type:

str

port_number

The number of Analysis Server port

Type:

str

model

Tabular Analysis Server port model of the Power BI file.

Type:

Tabular.Model

tables

A list of tables names inside the Power BI model.

Type:

list

resume_tables_and_columns(export_to_excel: bool = False) DataFrame

Method to resume all tables and columns of the model

Parameters:

export_to_excel (bool) – Export the dataframe as an excel file.

Returns:

A dataframe with information of tables and columns of

the Power BI data model.

Return type:

pd.DataFrame

resume_measures(export_to_excel: bool = False) DataFrame

Method to resume the measures of the model

Parameters:

export_to_excel (bool) – Export the dataframe as an excel file.

Returns:

A dataframe with information of measure of the Power

BI data model.

Return type:

pd.DataFrame

export_excel_measure_creator(excel_file_name: str = 'ppr_measure_creator') None

Method to export an auxiliar excel file to create measures.

The ppr_measure_creator file is intended to be used in conjunction with the add_measure_in_model method. The format of the excel table is perfectly suited to be read by pandas and used for adding measures.

Parameters:

excel_file_name (str, optional) – The name of excel file. Defaults to ‘ppr_measure_creator’.

import_excel_measure_creator(file_name: str = 'ppr_measure_creator.xlsx', sheet_name: str = 'Measure Creator', if_exists: Literal['warn', 'delete'] = 'warn')

Method to import measures from an excel file

This function read the sheet_name sheet of the file_name excel file and use the main columns to add measures in the model. The necessary columns are:

  • Table: The name of the table where the measure will be placed

  • Name: The name of the measure

  • Description: A description for the measure

  • Expression: The DAX expression of the measure

  • Display Folder: The folder where the measure will be placed

  • Format String: The format string of the measure

Parameters:
  • file_name (str) –

  • sheet_name (str, optional) – _description_. Defaults to ‘Measure Creator’.

add_measure_in_model(table_name: str, name: str, expression: str, display_folder: str = '', description: str = 'Created with ppr', format_string: str = '0', if_exists: Literal['warn', 'delete'] = 'warn')

Method to add a measure into Power BI model

This method works with clr. This collects the MeasureCollection of Table object of Model and add a measure with necessary fields.

Parameters:
  • table_name (str) – The name where measure will be placed

  • name (str) – The name of the measure

  • expression (str) – DAX expression of the measure

  • dispaly_folder (str, optional) – The table folder of the meausre. Defaults to “”.

  • description (str, optional) – A descrption for the measure. Defaults to ‘Created with ppr’.

  • format_string (str, optional) – The format string of the measure. Defaults to ‘0’.

  • if_exists (['warn', 'delete'], optional) – Action to do if the measure is already present in the model. Defaults to ‘warn’.

Raises:
  • ValueError – If the table isn’t found in the model.

  • Warning – If the measure already exists in the model.

class pypbireport.pbi.pbimodel.Column(table_name, column)

Represents a column in Power BI model

_name

The name of the column

Type:

str

_attrs_name

The attribute name for the column

Type:

str

table_name

The parent table name of the column

Type:

str

field_name

Name suited to visuals insert (Table.FieldName).

Type:

str

qualified_name

Name suited to measures (‘Table’[FieldName])

Type:

str

class pypbireport.pbi.pbimodel.Measure(table_name, measure)

Represents a measure in Power BI model

_name

The name of the measure.

Type:

str

_attrs_name

The attribute name for the measure.

Type:

str

table_name

The parent table name of the measure.

Type:

str

field_name

Name suited to visuals insert (Table.FieldName).

Type:

str

qualified_name

Name suited to measures (‘Table’[FieldName])

Type:

str

dax

The DAX expression of the measure.

Type:

str

class pypbireport.pbi.pbimodel.Table(table)

Represents a table in Power BI model

Dynamics attributes are setted for table, namely columns and measures objects of the table.

_name

The name of the table

Type:

str

_attrs_name

(str): The attribute name of the table

\*columns

The columns of the table. The names begins with c_.

Type:

Column

\*measures

The measures of the table. The names begins with m_

Type:

Measure