首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在C#中以编程方式更改文本字段?

如何在C#中以编程方式更改文本字段?
EN

Stack Overflow用户
提问于 2021-10-24 12:33:10
回答 1查看 105关注 0票数 0

我有一个PPT模板,其中我需要以编程方式替换一些文本字段的数据,从我的数据库,然后转换为pdf格式,并将其作为附件发送在电子邮件中。我不确定如何更改PowerPoint演示文稿中文本字段的内容。我认为需要使用OpenXML。请帮助我将动态数据输入到我的ppt模板中。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-10-24 14:50:01

我以前使用过微软的DocumentFormat.OpenXml,但使用的是word文件。我用它替换了Power Point文件中的一些文本。

下面是我的简单测试代码片段:

代码语言:javascript
运行
复制
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元素中被分成多个文本部分,必须编写一个逻辑来“收集”这些数据,并用一个文本元素替换它们,以我想要的新文本,或者可能你必须搜索其他后代类型。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69696762

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档