cbailiss / pivottabler

Create Pivot Tables natively in R

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Pivot table to Powerpoint

AkshataSalian opened this issue · comments

Hi, I am looking to export pivot table created using pivottabler package to powerpoint report (officer package). I have tried a lot of options like converting pivot to html & latex and then trying to add in slide, but nothing worked. pt$asDataFrame() works, but the table is no longer in pivot format. Is there a way to get the pivot table in exactly the pivot format as we get in pt$renderPivot()?

Below is a reproducible code:-
#---------------------------------------------------------------------------------------
library(pivottabler)
pt <- PivotTable$new()
pt$addData(bhmtrains)
pt$addColumnDataGroups("TrainCategory")
pt$addColumnDataGroups("PowerType")
pt$addRowDataGroups("TOC")
pt$defineCalculation(calculationName="TotalTrains", summariseExpression="n()")
pt$renderPivot()

library(officer)
library(tidyverse)
doc <- read_pptx()
doc <- doc %>% add_slide(layout = "Title and Content", master = "Office Theme") %>%
ph_with(value = "Test Pivot", location = ph_location_label(ph_label = "Title 1")) %>%
ph_with(value = pt$asDataFrame(), location = ph_location_label(ph_label = "Content Placeholder 2"),
alignment = "c")
print(doc, target = "test.pptx")
#---------------------------------------------------------------------------------------

I don't think this is possible - at least I don't know any simple way to do this.
The officer package only supports data frames (which can't represent either the data structure or formatting of a pivottabler table) and flextables (there is no easy way to convert a pivottabler to a flextable).

The api for flextable looks like it would support creating a representation of a pivottabler table, so I will keep this issue open as a request for a future enhancement. It will be a few weeks however before I will be able to implement this.

PivotTables can now be converted to PowerPoint with v1.5.3 of the pivottabler package.

Example:

# construct the table
library(pivottabler)
pt <- PivotTable$new()
pt$addData(bhmtrains)
pt$addColumnDataGroups("PowerType")
pt$addRowDataGroups("TOC")
pt$defineCalculation(calculationName="TotalTrains", summariseExpression="n()")
pt$evaluatePivot()

# convert to a basictabler table
library(basictabler)
tbl <- pt$asBasicTable()

# convert to flextable
library(flextable)
ft <- tbl$asFlexTable()

# save PowerPoint document
library(officer)
ppt <- read_pptx()
ppt <- add_slide(ppt, layout = "Title and Content", master = "Office Theme")
ppt <- ph_with(ppt, value = ft, location = ph_location_left()) 
print(ppt, target = "example_table_powerpoint.pptx")