用python给表格加边框_pythonptx:更改表格样式或向单元格添加边框

本文介绍了如何使用Python的pptx库将Pandas数据帧插入PowerPoint幻灯片,并尝试更改单元格边框样式。虽然默认样式无法直接设置单元格边框,但代码示例展示了如何调整表格的其他样式属性,如字体大小、颜色和背景色。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我已经开始编写一些代码来获取Pandas数据并将其放入PowerPoint幻灯片中。我使用的模板默认为中等样式2-强调文字颜色1,这很好,因为更改字体和背景相当容易,但是python pptx似乎没有实现允许更改单元格边框的部分。下面是我的代码,对任何解决方案开放。(改变XML或者改变模板的默认值来填充更好的样式对我来说是个不错的选择,但是还没有找到关于如何做的好的文档)。中号风格4将是我的理想,因为它正好有我要找的边界。在import pandas

import numpy

from pptx import Presentation

from pptx.util import Inches, Pt

from pptx.dml.color import RGBColor

#Template Location

tmplLoc = 'C:/Desktop/'

#Read in Template

prs = Presentation(tmplLoc+'Template.pptx')

#Import data as Pandas Dataframe - dummy data for now

df = pandas.DataFrame(numpy.random.randn(10,10),columns=list('ABCDEFGHIJ'))

#Determine Table Header

header = list(df.columns.values)

#Determine rows and columns

in_rows = df.shape[0]

in_cols = df.shape[1]

#Insert table from C1 template

slide_layout = prs.slide_layouts[11]

slide = prs.slides.add_slide(slide_layout)

#Set slide title

title_placeholder = slide.shapes.title

title_placeholder.text = "Slide Title"

#Augment placeholder to be a table

placeholder = slide.placeholders[1]

graphic_frame = placeholder.insert_table(rows = in_rows+1, cols = in_cols)

table = graphic_frame.table

#table.apply_style = 'MediumStyle4'

#table.apply_style = 'D7AC3CCA-C797-4891-BE02-D94E43425B78'

#Set column widths

table.columns[0].width = Inches(2.23)

table.columns[1].width = Inches(0.9)

table.columns[2].width = Inches(0.6)

table.columns[3].width = Inches(2)

table.columns[4].width = Inches(0.6)

table.columns[5].width = Inches(0.6)

table.columns[6].width = Inches(0.6)

table.columns[7].width = Inches(0.6)

table.columns[8].width = Inches(0.6)

table.columns[9].width = Inches(0.6)

#total_width = 2.23+0.9+0.6+2+0.6*6

#Insert data into table

for rows in xrange(in_rows+1):

for cols in xrange(in_cols):

#Write column titles

if rows == 0:

table.cell(rows, cols).text = header[cols]

table.cell(rows, cols).text_frame.paragraphs[0].font.size=Pt(14)

table.cell(rows, cols).text_frame.paragraphs[0].font.color.rgb = RGBColor(255, 255, 255)

table.cell(rows, cols).fill.solid()

table.cell(rows, cols).fill.fore_color.rgb=RGBColor(0, 58, 111)

#Write rest of table entries

else:

table.cell(rows, cols).text = str("{0:.2f}".format(df.iloc[rows-1,cols]))

table.cell(rows, cols).text_frame.paragraphs[0].font.size=Pt(10)

table.cell(rows, cols).text_frame.paragraphs[0].font.color.rgb = RGBColor(0, 0, 0)

table.cell(rows, cols).fill.solid()

table.cell(rows, cols).fill.fore_color.rgb=RGBColor(255, 255, 255)

#Write Table to File

prs.save('C:/Desktop/test.pptx')

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值