Python自動化辦公——讀取PPT內(nèi)容寫入word表格
一、需求分析
??由于我們知識圖譜課程需要將課堂小組匯報的PPT總結成word文檔,而我覺得一頁一頁復制PPT中的內(nèi)容比較麻煩,所以直接安排:讀PPT寫word
二、導入依賴
??需要操作PPT幻燈片和word文檔,所以需要導入docx 和pptx兩個包
pip install pptx
pip install docx
這里我的docx使用的是0.2.4版本
pptx使用的是0.6.21版本供參考
三、代碼
引入os、pptx和docx
import os
from pptx import Presentation
from docx import Document
from docx.shared import Inches
設置PPT文件路徑和Word文件路徑
ppt_file_path = 'streamlit.pptx'
word_file_path = '問答系統(tǒng).docx'
創(chuàng)建文檔對象
# 創(chuàng)建PPT文檔對象
prs = Presentation(ppt_file_path)
# 創(chuàng)建Word文檔對象
doc = Document()
在Word文檔中添加表格
table = doc.add_table(rows=1, cols=2)
hdr_cells = table.rows[0].cells
hdr_cells[0].text = 'Slide'
hdr_cells[1].text = 'Text'
讀取PPT中的每個幻燈片
for i, slide in enumerate(prs.slides):
# 獲取幻燈片中的所有文本內(nèi)容
text = ''
for shape in slide.shapes:
if not shape.has_text_frame:
continue
for paragraph in shape.text_frame.paragraphs:
for run in paragraph.runs:
text += run.text
# 將幻燈片和文本內(nèi)容寫入Word表格中
row_cells = table.add_row().cells
row_cells[0].text = f'Slide {i + 1}'
row_cells[1].text = text
最后保存word
# 將Word文檔保存到指定位置
doc.save(word_file_path)
完整代碼如下:
import os
from pptx import Presentation
from docx import Document
from docx.shared import Inches
# 設置PPT文件路徑和Word文件路徑
ppt_file_path = 'streamlit.pptx'
word_file_path = '問答系統(tǒng).docx'
# 創(chuàng)建PPT文檔對象
prs = Presentation(ppt_file_path)
# 創(chuàng)建Word文檔對象
doc = Document()
# 在Word文檔中添加表格
table = doc.add_table(rows=1, cols=2)
hdr_cells = table.rows[0].cells
hdr_cells[0].text = 'Slide'
hdr_cells[1].text = 'Text'
# 讀取PPT中的每個幻燈片
for i, slide in enumerate(prs.slides):
# 獲取幻燈片中的所有文本內(nèi)容
text = ''
for shape in slide.shapes:
if not shape.has_text_frame:
continue
for paragraph in shape.text_frame.paragraphs:
for run in paragraph.runs:
text += run.text
# 將幻燈片和文本內(nèi)容寫入Word表格中
row_cells = table.add_row().cells
row_cells[0].text = f'Slide {i + 1}'
row_cells[1].text = text
# 將Word文檔保存到指定位置
doc.save(word_file_path)
四、結果及總結
結果如上圖所示,將PPT中的內(nèi)容提取了出來并寫入了word表格。文章來源:http://www.zghlxwxcb.cn/news/detail-501320.html
也可以根據(jù)定制化需求自由編寫代碼,來實現(xiàn)書寫的格式。文章來源地址http://www.zghlxwxcb.cn/news/detail-501320.html
到了這里,關于python自動化辦公——讀取PPT寫入word表格的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!