本文整理匯總了Python中pptx.Presentation方法的典型用法代碼示例。如果您正苦於以下問題:Python pptx.Presentation方法的具體用法?Python pptx.Presentation怎麽用?Python pptx.Presentation使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類pptx
的用法示例。
在下文中一共展示了pptx.Presentation方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: pptx_to_text
# 需要導入模塊: import pptx [as 別名]
# 或者: from pptx import Presentation [as 別名]
def pptx_to_text(document_path, event, context):
import pptx
prs = pptx.Presentation(document_path)
paragraphs = []
for slide in prs.slides:
for shape in slide.shapes:
if not shape.has_text_frame: continue
paragraphs += [' '.join([run.text for run in paragraph.runs]) for paragraph in shape.text_frame.paragraphs]
#end for
#end for
return '\n\n'.join(paragraphs).strip()
#end def
示例2: replace_chart_data_in_prs
# 需要導入模塊: import pptx [as 別名]
# 或者: from pptx import Presentation [as 別名]
def replace_chart_data_in_prs(pres_path, slide_num, chart_name, df):
'''
This function 1) enters an existing powerpoint, 2) finds given slides, 3) finds given chart by name and
4) replaces the given chart's underlying data with new data in the form of a dataframe.
param: pres_path - takes the full path of target file
param: slide_num - takes a list of slides
param: chart_name - object name as it appears within powerpoint's Object Selection Pane
param: df - takes a list of pandas dataframe objects
'''
PRES_FOLDER_FOLDER = dirname(pres_path)
PRES_NAME = basename(pres_path).replace('.pptx','')
prs = Presentation(pres_path)
loop_counter=0
for i, sld in enumerate(prs.slides, start=1):
if i in slide_num:
for x, shp in enumerate(sld.shapes):
if shp.name == chart_name:
single_df = df[loop_counter]
chart_data = ChartData()
chart_data.categories = single_df.index
for col_idx, col in enumerate(single_df.columns):
chart_data.add_series(col, (single_df.ix[:, col_idx].values))
shp.chart.replace_data(chart_data)
loop_counter+=1
prs.save('{pres_path}\\{pres_name}_edited.pptx'.format(
pres_path=PRES_FOLDER_FOLDER,
pres_name=PRES_NAME))
示例3: generate_presentation_using_cli_arguments
# 需要導入模塊: import pptx [as 別名]
# 或者: from pptx import Presentation [as 別名]
def generate_presentation_using_cli_arguments(args) -> Tuple[Presentation, SlideDeck, str]:
"""Make a talk with the given topic."""
runtime_checker.check_runtime_environment()
# Print status details
logger.info("******************************************")
logger.info("Making {} slide talk on: {}".format(args.num_slides, args.topic))
return generate_presentation(
schema=args.schema,
slides=args.num_slides,
topic=args.topic,
title=args.title,
presenter=args.presenter,
parallel=args.parallel,
int_seed=args.int_seed,
print_logs=args.print_logs,
save_ppt=args.save_ppt,
open_ppt=args.open_ppt,
)
示例4: __init__
# 需要導入模塊: import pptx [as 別名]
# 或者: from pptx import Presentation [as 別名]
def __init__(self,filename=None,chart_type_default='COLUMN_CLUSTERED',**kwargs):
self.title=None
self.author=None
# self.filename = filename #導入一個存在的pptx文件
self.chart_type_default=chart_type_default
if filename is None:
if os.path.exists('template.pptx'):
prs=Presentation('template.pptx')
elif template_pptx is not None:
prs=Presentation(template_pptx)
else:
prs=Presentation()
else :
# 分離出路徑中的文件名
self.title=os.path.splitext(os.path.split(filename)[1])[0]
prs=Presentation(filename)
self.prs=prs
title_only_slide=self._layouts()
if title_only_slide:
layouts=title_only_slide[0]
else:
layouts=[0,0]
self.layouts_default=layouts
for k in kwargs:
setattr(self,k.lower(),kwargs[k])
示例5: ppt_section_slide
# 需要導入模塊: import pptx [as 別名]
# 或者: from pptx import Presentation [as 別名]
def ppt_section_slide(title, subtitle, file_path):
from pptx import Presentation
try:
prs = Presentation(file_path)
except:
prs = Presentation(r'C:\Users\adrose\Desktop\AMD PowerPoint Template.pptx')
picture_slide_layout = prs.slide_layouts[0]
slide = prs.slides.add_slide(picture_slide_layout)
# for x in slide.placeholders:
# print('%d %s' % (x.placeholder_format.idx, x.name))
title_placeholder = slide.placeholders[0]
subtitle_placeholder = slide.placeholders[1]
title_placeholder.text = title
subtitle_placeholder.text = subtitle
prs.save(file_path)
示例6: save_figs_to_ppt
# 需要導入模塊: import pptx [as 別名]
# 或者: from pptx import Presentation [as 別名]
def save_figs_to_ppt(figs, filename):
from pptx import Presentation
prs = Presentation()
title_slide_layout = prs.slide_layouts[0]
slide = prs.slides.add_slide(title_slide_layout)
title = slide.shapes.title
subtitle = slide.placeholders[1]
title.text = "Hello, World!"
subtitle.text = "python-pptx was here!"
prs.save('test.pptx')
示例7: __init__
# 需要導入模塊: import pptx [as 別名]
# 或者: from pptx import Presentation [as 別名]
def __init__(self):
self.presentation = Presentation(os.path.join(os.path.dirname(__file__), "template.pptx"))
self.slide_layout = self.presentation.slide_layouts[6]
self.slide = self.presentation.slides.add_slide(self.slide_layout)
self.shapes = self.slide.shapes
示例8: create_new_powerpoint
# 需要導入模塊: import pptx [as 別名]
# 或者: from pptx import Presentation [as 別名]
def create_new_powerpoint() -> Presentation:
return Presentation(get_powerpoint_template_file())
示例9: __init__
# 需要導入模塊: import pptx [as 別名]
# 或者: from pptx import Presentation [as 別名]
def __init__(self, path_to_presentation, slide_layout=None, shape_properties=None):
self.presentation = Presentation(path_to_presentation) # TODO PptxPainter - Path checking # type: Presentation
if slide_layout is None:
self.default_slide_layout = None
else:
self.default_slide_layout = self.set_slide_layout(slide_layout)
# Add all the dafault dicts to the class -
if shape_properties:
self._shape_properties = shape_properties
else:
self._shape_properties = PptxDefaults()
self.textbox = self._shape_properties.textbox
self.textbox_header = self._shape_properties.textbox_header
self.textbox_footer = self._shape_properties.textbox_footer
self.chart = self._shape_properties.chart
self.table = self._shape_properties.table
self.side_table = self._shape_properties.side_table
charts = self._shape_properties.charts
self.chart_bar = charts['bar']
self.chart_bar_stacked100 = charts['bar_stacked100']
self.chart_line = charts['line']
self.chart_column = charts['column']
self.chart_pie = charts['pie']
self.slide_kwargs = {
'textboxs': {},
'charts': {},
'tables': {},
'side_tables': {},
}
示例10: rename_duplicate_shape_names
# 需要導入模塊: import pptx [as 別名]
# 或者: from pptx import Presentation [as 別名]
def rename_duplicate_shape_names(pres_path, overwrite=True):
'''
Ensures all shapes have a unique name.
Only renames duplicates.
Compares shape names one slide at a time.
'''
file_name = basename(pres_path).split('.')[0]
file_path = dirname(pres_path)
prs = Presentation(pres_path)
for slide in prs.slides:
shape_names = []
for shape in slide.shapes:
shape_names.append(shape.name)
renamed_shapes = [x + "_" + str(i) if shape_names.count(x)>1 else x for i, x in enumerate(shape_names)]
for s_idx, shape in enumerate(slide.shapes):
shape.name = renamed_shapes[s_idx]
if overwrite:
prs.save('{pres_path}\\{pres_name}.pptx'.format(
pres_path=file_path,
pres_name=file_name))
else:
prs.save('{pres_path}\\{pres_name}_edited.pptx'.format(
pres_path=file_path,
pres_name=file_name))
示例11: get_chart_data_from_prs
# 需要導入模塊: import pptx [as 別名]
# 或者: from pptx import Presentation [as 別名]
def get_chart_data_from_prs(pres_path, slide_num, chart_name):
'''
This function 1) pulls a given chart's data and 2) returns it as a pandas dataframe object in a list
param: pres_path - full path of target file
param: slide_num - takes a list of slides
param: chart_name - object name as it appears within powerpoint's Object Selection Pane
'''
prs = Presentation(pres_path)
collection_of_dfs = []
for i, sld in enumerate(prs.slides, start=1):
if i in slide_num:
for x, shp in enumerate(sld.shapes):
if shp.name == chart_name:
plot = shp.chart.plots[0]
columns = []
data = []
for series in plot.series:
columns.append(str(series.name))
data.append(series.values)
data = np.array(data)
rows = np.array(plot.categories)
df = pd.DataFrame(data.T, index=rows, columns=columns)
collection_of_dfs.append(df)
return(collection_of_dfs)
示例12: pic_to_ppt
# 需要導入模塊: import pptx [as 別名]
# 或者: from pptx import Presentation [as 別名]
def pic_to_ppt(filename): #前提是圖片文件名全為數字,否則還需要修改
if not os.path.exists(filename):
os.mkdir(filename)
ppt = pptx.Presentation()
pic_path=[]
for i in os.walk(filename).__next__()[2]:
if i.endswith('.png'):
pic_path.append(i)
#若是不全為數字,則可嘗試運行下列代碼
# ls=[]
# for png in pic_path:
# s=''
# for item in png:
# if item<='9' and item>='0':
# s+=item
# ls.append(s+'.png')
# pic_path=ls
pic_path.sort(key=lambda item:int(item.split('.')[0]))
for i in pic_path:
i='{}/{}'.format(filename,i)
slide = ppt.slides.add_slide(ppt.slide_layouts[1])
slide.shapes.add_picture(i, Inches(0), Inches(0), Inches(10), Inches(7.5))
fname='{}/{}.pptx'.format(filename,filename)
ppt.save(fname)
print('生成的文件在 {} 文件夾下的 {}.ppt 中'.format(filename,filename))
示例13: df_to_powerpoint
# 需要導入模塊: import pptx [as 別名]
# 或者: from pptx import Presentation [as 別名]
def df_to_powerpoint(filename, df, **kwargs):
"""Converts a Pandas DataFrame to a table in a new, blank PowerPoint
presentation.
Creates a new PowerPoint presentation with the given filename, with a single
slide containing a single table with the Pandas DataFrame data in it.
The table is a standard Powerpoint table, and can easily be modified with
the Powerpoint tools, for example: resizing columns, changing formatting
etc.
Parameters
----------
filename: Filename to save the PowerPoint presentation as
df: pandas ``DataFrame``
DataFrame with the data
**kwargs
All other arguments that can be taken by ``df_to_table()`` (such as
``col_formatters`` or ``rounding``) can also be passed here.
Returns
-------
pptx.shapes.graphfrm.GraphicFrame
The python-pptx table (GraphicFrame) object that was created (which can
then be used to do further manipulation if desired)
"""
pres = Presentation()
blank_slide_layout = pres.slide_layouts[6]
slide = pres.slides.add_slide(blank_slide_layout)
table = df_to_table(slide, df, **kwargs)
pres.save(filename)
return table
示例14: main
# 需要導入模塊: import pptx [as 別名]
# 或者: from pptx import Presentation [as 別名]
def main():
parser = argparse.ArgumentParser(description = 'Edit pptx with text replace and csv import')
parser.add_argument('--template', help='template pptx file (required)', required=True)
parser.add_argument('--model', help='model object file with .json or .xlsx format', required=True)
parser.add_argument('--out', help='created pptx file (required)', required=True)
parser.add_argument('--debug', action='store_true', help='output verbose log')
parser.add_argument('--skip-model-not-found', action='store_true', help='skip if specified key is not found in the model')
opts = parser.parse_args()
if not len(log.handlers):
handler = logging.StreamHandler()
handler.setLevel(logging.DEBUG)
log.addHandler(handler)
if opts.debug:
log.setLevel(logging.DEBUG)
else:
log.setLevel(logging.INFO)
log.info(u"pptx-template version %s" % __version__)
if opts.model.endswith(u'.xlsx'):
slides = generate_whole_model(opts.model, {})
else:
if opts.model == u'-' and sys.version_info[0] == 3:
sys.stdin = TextIOWrapper(sys.stdin.buffer, encoding='utf-8')
with open(opts.model, 'r', encoding='utf-8') if opts.model != u'-' else sys.stdin as m:
models = json.load(m)
slides = models[u'slides']
log.info(u"Loading template pptx: %s" % opts.template)
ppt = Presentation(opts.template)
process_all_slides(slides, ppt, skip_model_not_found = opts.skip_model_not_found)
log.info(u"Writing pptx: %s" % opts.out)
ppt.save(opts.out)
示例15: build_presentation
# 需要導入模塊: import pptx [as 別名]
# 或者: from pptx import Presentation [as 別名]
def build_presentation(filename):
prs = Presentation()
slide_layout = prs.slide_layouts[6] # blank slide
slide = prs.slides.add_slide(slide_layout)
prs.save(filename)
return