使用 OpenXML SDK C# 以编程方式将脚注添加到 Word 文档

问题描述 投票:0回答:3

我需要使用 Open XML SDK 创建一个 Word 文档。我有文档文本和脚注。我正在使用下面的代码片段来创建 Word 文档。 我可以使用文本创建文档,但无法向其中添加脚注。 您能否告诉我们如何使用 Open Xml 以编程方式添加脚注

   public void CreateWordDocument()
   {

       using (MemoryStream DocxMemory = new MemoryStream())
       {
           using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(DocxMemory, WordprocessingDocumentType.Document, true))
           {
               // Add a main document part. 
               MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();
               // Create the document structure and add some text.
               this.AddSettingsToMainDocumentPart(mainPart);

               StyleDefinitionsPart part = mainPart.StyleDefinitionsPart;
               // If the Styles part does not exist, add it.  
               if (part == null)
               {
                   this.AddStylesPartToPackage(mainPart);
               }

               mainPart.Document = new Document();
               Body body = mainPart.Document.AppendChild(new Body());
               Paragraph Para = body.AppendChild(new Paragraph());
               Run run = Para.AppendChild(new Run());
               run.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Text("This is main text of the document"));

               var footnotesPart = mainPart.AddNewPart<FootnotesPart>("rId1");

               this.GenerateFooterPartContent(mainPart.FootnotesPart);
               mainPart.Document.Save();
               wordDocument.Close();

               MemoryStream Result = new MemoryStream();
               DocxMemory.Seek(0, SeekOrigin.Begin);
               DocxMemory.CopyTo(Result);
               Result.Position = 0;

               ////Citation processing
               byte[] BufferFileData = new byte[Result.Length];
               Result.Read(BufferFileData, 0, (int)Result.Length);
               File.WriteAllBytes("Output1.docx", BufferFileData);

           }
       }
   }

   private void AddSettingsToMainDocumentPart(MainDocumentPart part)
   {
       DocumentSettingsPart settingsPart = part.DocumentSettingsPart;
       if (settingsPart == null)
           settingsPart = part.AddNewPart<DocumentSettingsPart>();
       settingsPart.Settings = new Settings(
         new Compatibility(
           new CompatibilitySetting()
           {
               Name = new EnumValue<CompatSettingNameValues>
                       (CompatSettingNameValues.CompatibilityMode),
               Val = new StringValue("14"),
               Uri = new StringValue
                       ("http://schemas.microsoft.com/office/word")
           }
      )
   );
       settingsPart.Settings.Save();
   }
   private StyleDefinitionsPart AddStylesPartToPackage(MainDocumentPart mainPart)
   {
       StyleDefinitionsPart part;
       part = mainPart.AddNewPart<StyleDefinitionsPart>();
       Styles root = new Styles();
       root.Save(part);
       return part;
   }

   // Generates content of part.
   private void GenerateFooterPartContent(FootnotesPart part)
   {
       Footnotes footnotes1 = new Footnotes() { MCAttributes = new MarkupCompatibilityAttributes() { Ignorable = "w14 wp14" } };
       footnotes1.AddNamespaceDeclaration("wpc", "http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas");
       footnotes1.AddNamespaceDeclaration("mc", "http://schemas.openxmlformats.org/markup-compatibility/2006");
       footnotes1.AddNamespaceDeclaration("o", "urn:schemas-microsoft-com:office:office");
       footnotes1.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships");
       footnotes1.AddNamespaceDeclaration("m", "http://schemas.openxmlformats.org/officeDocument/2006/math");
       footnotes1.AddNamespaceDeclaration("v", "urn:schemas-microsoft-com:vml");
       footnotes1.AddNamespaceDeclaration("wp14", "http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing");
       footnotes1.AddNamespaceDeclaration("wp", "http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing");
       footnotes1.AddNamespaceDeclaration("w10", "urn:schemas-microsoft-com:office:word");
       footnotes1.AddNamespaceDeclaration("w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main");
       footnotes1.AddNamespaceDeclaration("w14", "http://schemas.microsoft.com/office/word/2010/wordml");
       footnotes1.AddNamespaceDeclaration("wpg", "http://schemas.microsoft.com/office/word/2010/wordprocessingGroup");
       footnotes1.AddNamespaceDeclaration("wpi", "http://schemas.microsoft.com/office/word/2010/wordprocessingInk");
       footnotes1.AddNamespaceDeclaration("wne", "http://schemas.microsoft.com/office/word/2006/wordml");
       footnotes1.AddNamespaceDeclaration("wps", "http://schemas.microsoft.com/office/word/2010/wordprocessingShape");

       Footnote footnote1 = new Footnote() { Type = FootnoteEndnoteValues.Separator, Id = -1 };

       Paragraph paragraph1 = new Paragraph() { RsidParagraphAddition = "003F1A60", RsidParagraphProperties = "00626544", RsidRunAdditionDefault = "003F1A60" };

       Run run1 = new Run();
       SeparatorMark separatorMark1 = new SeparatorMark();

       run1.Append(separatorMark1);

       paragraph1.Append(run1);

       footnote1.Append(paragraph1);

       Footnote footnote2 = new Footnote() { Type = FootnoteEndnoteValues.ContinuationSeparator, Id = 0 };

       Paragraph paragraph2 = new Paragraph() { RsidParagraphAddition = "003F1A60", RsidParagraphProperties = "00626544", RsidRunAdditionDefault = "003F1A60" };

       Run run2 = new Run();
       ContinuationSeparatorMark continuationSeparatorMark1 = new ContinuationSeparatorMark();

       run2.Append(continuationSeparatorMark1);

       paragraph2.Append(run2);

       footnote2.Append(paragraph2);

       Footnote footnote3 = new Footnote() { Id = 1 };

       Paragraph paragraph3 = new Paragraph() { RsidParagraphMarkRevision = "009774CC", RsidParagraphAddition = "00626544", RsidParagraphProperties = "00626544", RsidRunAdditionDefault = "00626544" };

       ParagraphProperties paragraphProperties1 = new ParagraphProperties();


       ParagraphMarkRunProperties paragraphMarkRunProperties1 = new ParagraphMarkRunProperties();
       RunFonts runFonts1 = new RunFonts() { AsciiTheme = ThemeFontValues.MinorHighAnsi, HighAnsiTheme = ThemeFontValues.MinorHighAnsi, ComplexScriptTheme = ThemeFontValues.MinorHighAnsi };
       FontSize fontSize1 = new FontSize() { Val = "24" };
       FontSizeComplexScript fontSizeComplexScript1 = new FontSizeComplexScript() { Val = "24" };

       paragraphMarkRunProperties1.Append(runFonts1);
       paragraphMarkRunProperties1.Append(fontSize1);
       paragraphMarkRunProperties1.Append(fontSizeComplexScript1);
       paragraphProperties1.Append(paragraphMarkRunProperties1);

       Run run3 = new Run() { RsidRunProperties = "009774CC" };

       RunProperties runProperties1 = new RunProperties();
       RunFonts runFonts2 = new RunFonts() { AsciiTheme = ThemeFontValues.MinorHighAnsi, HighAnsiTheme = ThemeFontValues.MinorHighAnsi, ComplexScriptTheme = ThemeFontValues.MinorHighAnsi };
       FontSize fontSize2 = new FontSize() { Val = "24" };
       FontSizeComplexScript fontSizeComplexScript2 = new FontSizeComplexScript() { Val = "24" };
       VerticalTextAlignment verticalTextAlignment1 = new VerticalTextAlignment() { Val = VerticalPositionValues.Superscript };

       runProperties1.Append(runFonts2);
       runProperties1.Append(fontSize2);
       runProperties1.Append(fontSizeComplexScript2);
       runProperties1.Append(verticalTextAlignment1);
       Text text1 = new Text();
       text1.Text = "1";

       run3.Append(runProperties1);
       run3.Append(text1);

      Run run4 = new Run() { RsidRunProperties = "009774CC" };

       RunProperties runProperties2 = new RunProperties();
       RunFonts runFonts3 = new RunFonts() { AsciiTheme = ThemeFontValues.MinorHighAnsi, HighAnsiTheme = ThemeFontValues.MinorHighAnsi, ComplexScriptTheme = ThemeFontValues.MinorHighAnsi };

       runProperties2.Append(runFonts3);
       Text text2 = new Text() { Space = SpaceProcessingModeValues.Preserve };
       text2.Text = " ";

       run4.Append(runProperties2);
       run4.Append(text2);

      Run run5 = new Run() { RsidRunProperties = "009774CC", RsidRunAddition = "009774CC" };

       RunProperties runProperties3 = new RunProperties();
       RunFonts runFonts4 = new RunFonts() { AsciiTheme = ThemeFontValues.MinorHighAnsi, HighAnsiTheme = ThemeFontValues.MinorHighAnsi, ComplexScriptTheme = ThemeFontValues.MinorHighAnsi };
       FontSize fontSize3 = new FontSize() { Val = "21" };
       FontSizeComplexScript fontSizeComplexScript3 = new FontSizeComplexScript() { Val = "21" };

       runProperties3.Append(runFonts4);
       runProperties3.Append(fontSize3);
       runProperties3.Append(fontSizeComplexScript3);
       Text text3 = new Text();
       text3.Text = "This is the foot note text";

       run5.Append(runProperties3);
       run5.Append(text3);

       paragraph3.Append(paragraphProperties1);
       paragraph3.Append(run3);
       paragraph3.Append(run4);
       paragraph3.Append(run5);

       footnote3.Append(paragraph3);

       footnotes1.Append(footnote1);
       footnotes1.Append(footnote2);
       footnotes1.Append(footnote3);
       part.Footnotes = footnotes1;
   }
c# openxml footnotes
3个回答
1
投票

我设法使用以下代码添加脚注。 我希望这有帮助。

        var ms = new MemoryStream();
        using (WordprocessingDocument myDoc = WordprocessingDocument.Create(ms, WordprocessingDocumentType.Document))
        {
            MainDocumentPart mainPart = myDoc.AddMainDocumentPart();
            var footPart = mainPart.AddNewPart<FootnotesPart>();
            footPart.Footnotes = new Footnotes();

            mainPart.Document = new Document();
            Body body = new Body();
            var p = new Paragraph();
            var r = new Run();
            var t = new Text("123");
            r.Append(t);
            p.Append(r);

            // ADD THE FOOTNOTE
            var footnote = new Footnote();
            footnote.Id = 1;
            var p2 = new Paragraph();
            var r2 = new Run();
            var t2 = new Text();
            t2.Text = "My FootNote Content";
            r2.Append(t2);
            p2.Append(r2);
            footnote.Append(p2);
            footPart.Footnotes.Append(footnote);

            // ADD THE FOOTNOTE REFERENCE
            var fref = new FootnoteReference();
            fref.Id = 1;
            var r3 = new Run();
            r3.RunProperties = new RunProperties();
            var s3 = new VerticalTextAlignment();
            s3.Val = VerticalPositionValues.Superscript;
            r3.RunProperties.Append(s3);
            r3.Append(fref);
            p.Append(r3);

            body.Append(p);
            mainPart.Document.Append(body);
            mainPart.Document.Save();
            ms.Flush();
        }
        return ms.ToArray();

0
投票

我不是 OpenXML 专家,但我认为您缺少在正文中添加对脚注的实际引用,我像这样调整了您的代码,现在我在文档中获得了脚注。希望它对您有所帮助,或者至少可以帮助您入门。

Run run = Para.AppendChild(new Run());
run.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Text("This is main text of the document"));
var footnoteref = new FootnoteReference() { Id = 1 };
run.Append(footnoteref);

0
投票

这里之前的解决方案对我来说不能正常工作。脚注并没有自动与雅尼斯的答案一起编号。解决方案是向脚注添加一个新的 FootnotReferenceMark,以便在文本和脚注中自动编号引用。

// Create and append footnote
Footnote footnote = new Footnote() { Id = footnoteId };
// Create and insert footnote reference
//Make fontsize 20 and superscript
ParagraphProperties paraProps = new ParagraphProperties();
ParagraphStyleId styleId = new ParagraphStyleId() { Val = "FootnoteText" }; // Style for footnote text
paraProps.Append(styleId);
Paragraph para = new Paragraph(paraProps);
Run footnoteTextRun = new Run();
var footnoteTextContent = new Text(footnoteText);
footnoteTextContent.Space = SpaceProcessingModeValues.Preserve;
footnoteTextRun.Append(footnoteTextContent);

//Add FootnoteReferenceMark
Run footnoteReferenceMarkRun = new Run();
footnoteReferenceMarkRun.RunProperties = new RunProperties(new FontSize() { Val = "20" }, new VerticalTextAlignment() { Val = VerticalPositionValues.Superscript });
var FnreferenceMark = new FootnoteReferenceMark();
footnoteReferenceMarkRun.Append(FnreferenceMark);
para.Append(footnoteReferenceMarkRun);
para.Append(footnoteTextRun);
footnote.Append(para);
docMainPart.FootnotesPart.Footnotes.Append(footnote);

// Add footnote reference to the body text
var reference = new FootnoteReference() { Id = footnoteId };
Run footnoteReferenceBodyRun = new Run();
footnoteReferenceBodyRun.RunProperties = new RunProperties(new FontSize() { Val = "24" }, new VerticalTextAlignment() { Val = VerticalPositionValues.Superscript });
footnoteReferenceBodyRun.Append(reference);
run.Parent.InsertAfter(footnoteReferenceBodyRun, run);
© www.soinside.com 2019 - 2024. All rights reserved.