質問

OpenXML SDK 2.0 CTP を使用して、プログラムで Word ドキュメントを作成しようとしています。私の文書には箇条書きリストを挿入する必要があり、リストの一部の要素には下線を引く必要があります。これどうやってするの?

役に立ちましたか?

解決

OpenXML のリストは少しわかりにくいです。

があります 番号付け定義部品 ドキュメント内のすべてのリストについて説明します。これには、リストの表示方法 (箇条書き、番号付けなど) に関する情報と、各リストへの ID の割り当てが含まれています。

それから、 メインドキュメントパート, 作成するリスト内の項目ごとに、新しい段落を追加し、その段落に必要なリストの ID を割り当てます。

したがって、次のような箇条書きリストを作成します。

  • こんにちは、
  • 世界!

まず NumberingDefinitionsPart を作成する必要があります。

NumberingDefinitionsPart numberingPart =
  mainDocumentPart.AddNewPart<NumberingDefinitionsPart>("someUniqueIdHere");

Numbering element = 
  new Numbering(
    new AbstractNum(
      new Level(
        new NumberingFormat() {Val = NumberFormatValues.Bullet},
        new LevelText() {Val = "·"}
      ) {LevelIndex = 0}
    ){AbstractNumberId = 1},
    new NumberingInstance(
      new AbstractNumId(){Val = 1}
    ){NumberID = 1});

element.Save(numberingPart);

次に、段落プロパティを除き、通常どおり MainDocumentPart を作成し、番号付け ID を割り当てます。

MainDocumentPart mainDocumentPart =
  package.AddMainDocumentPart();

Document element = 
  new Document(
    new Body(
      new Paragraph(
        new ParagraphProperties(
          new NumberingProperties(
            new NumberingLevelReference(){ Val = 0 },
            new NumberingId(){ Val = 1 })),
        new Run(
          new RunProperties(),
          new Text("Hello, "){ Space = "preserve" })),
      new Paragraph(
        new ParagraphProperties(
          new NumberingProperties(
            new NumberingLevelReference(){ Val = 0 },
            new NumberingId(){ Val = 1 })),
        new Run(
          new RunProperties(),
          new Text("world!"){ Space = "preserve" }))));

element.Save(mainDocumentPart);

利用可能なオプションについては、より詳しい説明があります。 OpenXML リファレンス ガイド セクション2.9で説明します。

他のヒント

私は私が文書に複数の箇条書きリストを追加できるようになる何かをしたかったです。しばらくの間、私の机のに対して私の頭を叩いた後、私は別の記事の束を組み合わせて、オープンXML SDK 2.0 Productityツールで私の文書を検査するために管理し、いくつかのものを考え出しました。それが生成するドキュメントはバージョンによって 2.0 の検証に合格しますSDK生産性ツールのと 2.5 に。

ここでは、コードです。うまくいけば、それは誰かいくつかの時間と悪化を保存します。

使用方法:

const string fileToCreate = "C:\\temp\\bulletTest.docx";

 if (File.Exists(fileToCreate))
    File.Delete(fileToCreate);

var writer = new SimpleDocumentWriter();
List<string> fruitList = new List<string>() { "Apple", "Banana", "Carrot"};
writer.AddBulletList(fruitList);
writer.AddParagraph("This is a spacing paragraph 1.");

List<string> animalList = new List<string>() { "Dog", "Cat", "Bear" };
writer.AddBulletList(animalList);
writer.AddParagraph("This is a spacing paragraph 2.");

List<string> stuffList = new List<string>() { "Ball", "Wallet", "Phone" };
writer.AddBulletList(stuffList);
writer.AddParagraph("Done.");

writer.SaveToFile(fileToCreate);

ステートメントを使用します:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;    

コード

public class SimpleDocumentWriter : IDisposable
{
    private MemoryStream _ms;
    private WordprocessingDocument _wordprocessingDocument;

    public SimpleDocumentWriter()
    {
        _ms = new MemoryStream();
        _wordprocessingDocument = WordprocessingDocument.Create(_ms, WordprocessingDocumentType.Document);
        var mainDocumentPart = _wordprocessingDocument.AddMainDocumentPart();
        Body body = new Body();
        mainDocumentPart.Document = new Document(body);
    }

    public void AddParagraph(string sentence)
    {
        List<Run> runList = ListOfStringToRunList(new List<string> { sentence});
        AddParagraph(runList);
    }
    public void AddParagraph(List<string> sentences)
    {
        List<Run> runList = ListOfStringToRunList(sentences);
        AddParagraph(runList);
    }

    public void AddParagraph(List<Run> runList)
    {
        var para = new Paragraph();
        foreach (Run runItem in runList)
        {
            para.AppendChild(runItem);
        }

        Body body = _wordprocessingDocument.MainDocumentPart.Document.Body;
        body.AppendChild(para);
    }

    public void AddBulletList(List<string> sentences)
    {
        var runList = ListOfStringToRunList(sentences);

        AddBulletList(runList);
    }


    public void AddBulletList(List<Run> runList)
    {
        // Introduce bulleted numbering in case it will be needed at some point
        NumberingDefinitionsPart numberingPart = _wordprocessingDocument.MainDocumentPart.NumberingDefinitionsPart;
        if (numberingPart == null)
        {
            numberingPart = _wordprocessingDocument.MainDocumentPart.AddNewPart<NumberingDefinitionsPart>("NumberingDefinitionsPart001");
            Numbering element = new Numbering();
            element.Save(numberingPart);
        }

        // Insert an AbstractNum into the numbering part numbering list.  The order seems to matter or it will not pass the 
        // Open XML SDK Productity Tools validation test.  AbstractNum comes first and then NumberingInstance and we want to
        // insert this AFTER the last AbstractNum and BEFORE the first NumberingInstance or we will get a validation error.
        var abstractNumberId = numberingPart.Numbering.Elements<AbstractNum>().Count() + 1;
        var abstractLevel = new Level(new NumberingFormat() {Val = NumberFormatValues.Bullet}, new LevelText() {Val = "·"}) {LevelIndex = 0};
        var abstractNum1 = new AbstractNum(abstractLevel) {AbstractNumberId = abstractNumberId};

        if (abstractNumberId == 1)
        {
            numberingPart.Numbering.Append(abstractNum1);
        }
        else
        {
            AbstractNum lastAbstractNum = numberingPart.Numbering.Elements<AbstractNum>().Last();
            numberingPart.Numbering.InsertAfter(abstractNum1, lastAbstractNum);
        }

        // Insert an NumberingInstance into the numbering part numbering list.  The order seems to matter or it will not pass the 
        // Open XML SDK Productity Tools validation test.  AbstractNum comes first and then NumberingInstance and we want to
        // insert this AFTER the last NumberingInstance and AFTER all the AbstractNum entries or we will get a validation error.
        var numberId = numberingPart.Numbering.Elements<NumberingInstance>().Count() + 1;
        NumberingInstance numberingInstance1 = new NumberingInstance() {NumberID = numberId};
        AbstractNumId abstractNumId1 = new AbstractNumId() {Val = abstractNumberId};
        numberingInstance1.Append(abstractNumId1);

        if (numberId == 1)
        {
            numberingPart.Numbering.Append(numberingInstance1);
        }
        else
        {
            var lastNumberingInstance = numberingPart.Numbering.Elements<NumberingInstance>().Last();
            numberingPart.Numbering.InsertAfter(numberingInstance1, lastNumberingInstance);
        }

        Body body = _wordprocessingDocument.MainDocumentPart.Document.Body;

        foreach (Run runItem in runList)
        {
            // Create items for paragraph properties
            var numberingProperties = new NumberingProperties(new NumberingLevelReference() {Val = 0}, new NumberingId() {Val = numberId});
            var spacingBetweenLines1 = new SpacingBetweenLines() { After = "0" };  // Get rid of space between bullets
            var indentation = new Indentation() { Left = "720", Hanging = "360" };  // correct indentation 

            ParagraphMarkRunProperties paragraphMarkRunProperties1 = new ParagraphMarkRunProperties();
            RunFonts runFonts1 = new RunFonts() { Ascii = "Symbol", HighAnsi = "Symbol" };
            paragraphMarkRunProperties1.Append(runFonts1);

            // create paragraph properties
            var paragraphProperties = new ParagraphProperties(numberingProperties, spacingBetweenLines1, indentation, paragraphMarkRunProperties1);

            // Create paragraph 
            var newPara = new Paragraph(paragraphProperties);

            // Add run to the paragraph
            newPara.AppendChild(runItem);

            // Add one bullet item to the body
            body.AppendChild(newPara);
        }
    }


    public void Dispose()
    {
        CloseAndDisposeOfDocument();
        if (_ms != null)
        {
            _ms.Dispose();
            _ms = null;
        }
    }

    public MemoryStream SaveToStream()
    {
        _ms.Position = 0;
        return _ms;
    }

    public void SaveToFile(string fileName)
    {
        if (_wordprocessingDocument != null)
        {
            CloseAndDisposeOfDocument();
        }

        if (_ms == null)
            throw new ArgumentException("This object has already been disposed of so you cannot save it!");

        using (var fs = File.Create(fileName))
        {
            _ms.WriteTo(fs);
        }
    }

    private void CloseAndDisposeOfDocument()
    {
        if (_wordprocessingDocument != null)
        {
            _wordprocessingDocument.Close();
            _wordprocessingDocument.Dispose();
            _wordprocessingDocument = null;
        }
    }

    private static List<Run> ListOfStringToRunList(List<string> sentences)
    {
        var runList = new List<Run>();
        foreach (string item in sentences)
        {
            var newRun = new Run();
            newRun.AppendChild(new Text(item));
            runList.Add(newRun);
        }

        return runList;
    }
}
コメントで述べたように、それは代わりに新しいのNumの新しいNumberingInstance((であることを除い

上記のアダムの答えは正しいです。

あなたが複数のリストを持っている場合は、

また、あなたが複数の番号の要素を持っている必要があります(それ自身のID例えば1、2でそれぞれ、3など - 。ドキュメント内の各リストに1つは、これはとの問題ではないようですそれはそれは同じリストだと思いますので、箇条書きのリストが、番号付きリストは、(1で再度やり直すと対照的に)同じ番号のシーケンスを使用して継続しますNumberingIdは、このようなあなたのパラグラフで参照する必要があります。

ParagraphProperties paragraphProperties1 = new ParagraphProperties();
ParagraphStyleId paragraphStyleId1 = new ParagraphStyleId() { Val = "ListParagraph" };
NumberingProperties numberingProperties1 = new NumberingProperties();
NumberingLevelReference numberingLevelReference1 = new NumberingLevelReference() { Val = 0 };

NumberingId numberingId1 = new NumberingId(){ Val = 1 }; //Val is 1, 2, 3 etc based on your numberingid in your numbering element
numberingProperties1.Append(numberingLevelReference1);
numberingProperties1.Append(numberingId1);
paragraphProperties1.Append(paragraphStyleId1);
paragraphProperties1.Append(numberingProperties1);

レベル要素の子供たちは弾丸の種類、およびインデントに影響を持つことになります。 私はレベル要素にこれを追加するまで、私の弾丸は小さすぎた。

new NumberingSymbolRunProperties(
    new RunFonts() { Hint = FontTypeHintValues.Default, Ascii = "Symbol", HighAnsi =   "Symbol" })
私もレベル要素にこの要素を追加するまで、

インデントが問題だっます:

new PreviousParagraphProperties(
  new Indentation() { Left = "864", Hanging = "360" })

そして、あなたは私のようにしている場合 - あなたは両方の状況を処理するために、このコードを使用したい場合があり、テンプレートからドキュメントを作成する - あなたのテンプレートがない、または任意の番号の定義が含まれていないときます:

// Introduce bulleted numbering in case it will be needed at some point
NumberingDefinitionsPart numberingPart = document.MainDocumentPart.NumberingDefinitionsPart;
if (numberingPart == null)
{
    numberingPart = document.MainDocumentPart.AddNewPart<NumberingDefinitionsPart>("NumberingDefinitionsPart001");
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top