[英]How to change text field in a PPT programmatically in C#?
我有一個 PPT 模板,我需要在其中以編程方式用來自我的數據庫的數據替換一些文本字段,然后將 ppt 轉換為 pdf 並將其作為電子郵件附件發送。 我不確定如何更改 PowerPoint 演示文稿中文本字段的內容。 我認為需要使用 OpenXML。 請幫助我將動態數據輸入到我的 ppt 模板中。
我以前使用過 Microsoft 的DocumentFormat.OpenXml
,但使用的是 word 文件。 我用它來替換 Power Point 文件中的一些文本。
這是我的簡單測試代碼片段:
static void Main(string[] args)
{
// just gets me the current location of the assembly to get a full path
string fileName = GetFilePath("Resource\\Template.pptx");
// open the presentation in edit mode -> the bool parameter stands for 'isEditable'
using (PresentationDocument document = PresentationDocument.Open(fileName, true))
{
// going through the slides of the presentation
foreach (SlidePart slidePart in document.PresentationPart.SlideParts)
{
// searching for a text with the placeholder i want to replace
DocumentFormat.OpenXml.Drawing.Text text =
slidePart.RootElement.Descendants<DocumentFormat.OpenXml.Drawing.Text>().FirstOrDefault(x => x.Text == "[[TITLE]]");
// change the text
if (text != null)
text.Text = "My new cool title";
// searching for the second text with the placeholder i want to replace
text =
slidePart.RootElement.Descendants<DocumentFormat.OpenXml.Drawing.Text>().FirstOrDefault(x => x.Text == "[[SUBTITLE]]");
// change the text
if (text != null)
text.Text = "My new cool sub-title";
}
document.Save();
}
}
在我的情況下,我有一個簡單的演示文稿,其中包含一張幻燈片,在文本字段中,我用此文本替換了條目“[[TITLE]]”和“[[SUBTITLE]]”。
對於我的測試文件,這運行良好,但也許您需要為特定文件采用/更改某些內容。 例如,在 Word 中,我有時將文本拆分為 Run 元素內的多個文本部分,並且必須編寫一個邏輯來“收集”這些數據,並將它們替換為一個文本元素,其中包含我想要的新文本,或者您可能有搜索其他后代類型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.