在Java程式設計中,如何在PPT中的幻燈片上格式化文字?
注意:需要存取網址:http://poi.apache.org/download.html , 下載一個Apache POI軟體包。這裡下載最新版本:poi-bin-3.17-20170915.tar.gz解壓並全部匯入 。
需要匯入全部包,如下圖所示 -
以下是使用Java在PPT中的幻燈片上格式化文字的程式。
package com.yiibai;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.xslf.usermodel.SlideLayout;
import org.apache.poi.xslf.usermodel.XMLSlideShow;
import org.apache.poi.xslf.usermodel.XSLFSlide;
import org.apache.poi.xslf.usermodel.XSLFSlideLayout;
import org.apache.poi.xslf.usermodel.XSLFSlideMaster;
import org.apache.poi.xslf.usermodel.XSLFTextParagraph;
import org.apache.poi.xslf.usermodel.XSLFTextRun;
import org.apache.poi.xslf.usermodel.XSLFTextShape;
public class FormatTextPPT {
public static void main(String args[]) throws IOException {
// creating an empty presentation
XMLSlideShow ppt = new XMLSlideShow();
// getting the slide master object
// XSLFSlideMaster slideMaster = ppt.getSlideMasters()[0];
java.util.List<XSLFSlideMaster> sl = ppt.getSlideMasters();
XSLFSlideMaster slideMaster = sl.get(0);
// select a layout from specified list
XSLFSlideLayout slidelayout = slideMaster.getLayout(SlideLayout.TITLE_AND_CONTENT);
// creating a slide with title and content layout
XSLFSlide slide = ppt.createSlide(slidelayout);
// selection of title place holder
XSLFTextShape body = slide.getPlaceholder(1);
// clear the existing text in the slide
body.clearText();
// adding new paragraph
XSLFTextParagraph paragraph = body.addNewTextParagraph();
// formatting line 1
XSLFTextRun run1 = paragraph.addNewTextRun();
run1.setText(" 這是紅色的一行文字字串 ");
// setting color to the text
run1.setFontColor(java.awt.Color.red);
// setting font size to the text
run1.setFontSize(24.00);
// moving to the next line
paragraph.addLineBreak();
// formatting line 2
XSLFTextRun run2 = paragraph.addNewTextRun();
run2.setText(" 這是一行加粗的字串 ");
run2.setFontColor(java.awt.Color.CYAN);
// making the text bold
run2.setBold(true);
paragraph.addLineBreak();
// formatting line 3
XSLFTextRun run3 = paragraph.addNewTextRun();
run3.setText(" 這是加了劃線的字串");
run3.setFontSize(12.00);
// making the text italic
run3.setItalic(true);
// strike through the text
run3.setStrikethrough(true);
paragraph.addLineBreak();
// formatting line 4
XSLFTextRun run4 = paragraph.addNewTextRun();
run4.setText(" 這是加了下劃線的文字 ");
run4.setUnderlined(true);
// underlining the text
paragraph.addLineBreak();
// creating a file object
File file = new File("FormatedText.pptx");
FileOutputStream out = new FileOutputStream(file);
// saving the changes to a file
ppt.write(out);
out.close();
System.out.println("PPT created");
}
}
執行上面範例程式碼,得到以下結果 -
PPT created
這就建立一個PPT檔案:FormatedText.pptx了,如下所示 -