我有一个PPT模板,其中我需要以编程方式替换一些文本字段的数据,从我的数据库,然后转换为pdf格式,并将其作为附件发送在电子邮件中。我不确定如何更改PowerPoint演示文稿中文本字段的内容。我认为需要使用OpenXML。请帮助我将动态数据输入到我的ppt模板中。
发布于 2021-10-24 14:50:01
我以前使用过微软的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元素中被分成多个文本部分,必须编写一个逻辑来“收集”这些数据,并用一个文本元素替换它们,以我想要的新文本,或者可能你必须搜索其他后代类型。
https://stackoverflow.com/questions/69696762
复制相似问题