1

私はこの状況を持っています:

ユーザーは自分のページにエディターを持っており、テキストを入力します (色、書式設定、ハイパーリンクを使用し、写真を追加することもできます)。[送信] をクリックすると、エディターからのデータ (適切な形式で) が Microsoft Office Word ドキュメントの特定のプレースホルダーに送信される必要があります。

OpenXml SDK を使用してドキュメントに書き込み、HtmlToOpenXml を試して html を読み取れるようにしました。

私は HtmlToOpenXml を使用し、(ユーザーからの) html 文字列からいくつかの段落を見つけたので、それらをコンテンツ コントロールに挿入する必要があります。コントロールを見つけて追加する方法を知っていますか(可能であれば)

4

1 に答える 1

0

私はこれを修正することができました。これが私が使用したコードです

            //name of the file which will be saved
            const string filename = "test.docx";
            //html string to be inserted and rendered in the word document
            string html = @"<b>Test</b>"; 
            //the Html2OpenXML dll supports all the common html tags

            //open the template document with the content controls in it(in my case I used Richtext Field Content Control)
            byte[] byteArray = File.ReadAllBytes("..."); // template path

            using (MemoryStream generatedDocument = new MemoryStream())
            {
                generatedDocument.Write(byteArray, 0, byteArray.Length);

                using (WordprocessingDocument doc = WordprocessingDocument.Open(generatedDocument, true))
                {

                    MainDocumentPart mainPart = doc.MainDocumentPart;
                    //just in case
                    if (mainPart == null)
                    {
                        mainPart = doc.AddMainDocumentPart();
                        new Document(new Body()).Save(mainPart);
                    }

                    HtmlConverter converter = new HtmlConverter(mainPart);
                    Body body = mainPart.Document.Body;

                    //sdtElement is the Content Control we need. 
                    //Html is the name of the placeholder we are looking for
                    SdtElement sdtElement = doc.MainDocumentPart.Document.Descendants<SdtElement>()
                        .Where(
                            element =>
                            element.SdtProperties.GetFirstChild<SdtAlias>() != null &&
                            element.SdtProperties.GetFirstChild<SdtAlias>().Val == "Html").FirstOrDefault();

                    //the HtmlConverter returns a set of paragraphs.
                    //in them we have the data which we want to insert in the document with it's formating
                    //After that we just need to append all paragraphs to the Content Control and save the document
                    var paragraphs = converter.Parse(html);

                    for (int i = 0; i < paragraphs.Count; i++)
                    {
                        sdtElement.Append(paragraphs[i]);
                    }

                    mainPart.Document.Save();
                }

                File.WriteAllBytes(filename, generatedDocument.ToArray());
            }
于 2013-09-26T06:18:14.207 に答える