From 563d9053a4208c39e99a72d19ae44050d8b8dbe5 Mon Sep 17 00:00:00 2001 From: kine Date: Sun, 13 Oct 2019 10:15:08 +0200 Subject: [PATCH] Adding replace_table method --- pptx_blueprint/__init__.py | 47 ++++++++++++++++++++++++++++++++++++-- 1 file changed, 45 insertions(+), 2 deletions(-) diff --git a/pptx_blueprint/__init__.py b/pptx_blueprint/__init__.py index 0bc402b..22492bc 100644 --- a/pptx_blueprint/__init__.py +++ b/pptx_blueprint/__init__.py @@ -38,14 +38,57 @@ def replace_picture(self, label: str, filename: __Pathlike): """ pass - def replace_table(self, label: str, data): + def replace_table(self, label: str, data, header=False, rownames=False): """Replaces rectangle placeholders on one or many slides. Args: label (str): label of the placeholder (without curly braces) data (pandas.DataFrame): table to be inserted into the presentation """ - pass + assert isinstance(data, pandas.dataframe) + + shapes_to_replace = self._find_shapes(label) + + rows, cols = data.shape + if header: rows += 1 + if rownames: cols += 1 + + for old_shape in shapes_to_replace: + slide_shapes = old_shape._parent + table = slide_shapes.add_table( + rows, + cols, + old_shape.left, + old_shape.top, + old_shape.width, + old_shape.height + ).table + + # set column widths + col_width = Length(old_shape.width/cols) + for i in range(len(table.columns)): + table.columns[i].width = col_width + + ## fill the table + for c in range(data.shape[1]): + for r in range(data.shape[0]): + if header and r == 0: + c_temp = c + ## when rownames, skip first column + if rownames: c_temp += 1 + table.cell(r, c_temp).text = data.columns[c] + if rownames and c == 0: + r_temp = r + ## when header, skip first row + if header: r_temp += 1 + table.cell(r_temp, c).text = str(data.index[r]) + ## fill table body + r_shape = r + if header: r_shape += 1 + c_shape = c + if rownames: c_shape += 1 + table.cell(r_shape, c_shape).text = str(data.iloc[r, c]) + def save(self, filename: __Pathlike): """Saves the updated pptx to the specified filepath.