[英]OpenXml-SDK: How to insert Plaintext with CarriageReturn/Linefeed
Currently I´m having a Word-Template with an RTF-FormField in it, in this FormField I want to insert Plaintext that comes from a MSSQL-Database. 当前,我有一个带有RTF-FormField的Word模板,在此FormField中,我想插入来自MSSQL数据库的纯文本。
With this Method I´m setting the Content of any FormField in my Document(including my RTF-FormField) 通过这种方法,我可以设置文档中任何FormField的内容(包括RTF-FormField)
public static void SetContentControlValue(this WordprocessingDocument doc, string name, string value)
{
var main = doc.MainDocumentPart;
var stdRuns = main.Document.Body
.Descendants<SdtRun>()
.Where(r => r.SdtProperties.GetFirstChild<Tag>().Val.Value.ToLower().Equals(name))
.ToList();
stdRuns.ForEach(c => c.Descendants<Text>().First().Text = value);
main.Document.Body
.Descendants<SdtBlock>()
.Where(r => r.SdtProperties.GetFirstChild<Tag>().Val.Value.ToLower().Equals(name))
.ToList()
.ForEach(c => c.Descendants<Text>().First().Text = value);
}
Unfortunately it swallows CarriageReturn/Linefeed 不幸的是,它吞没了回车/换行
I tried to do it this way 我试图这样做
var run = new SdtRun();
string[] newLineArray = { Environment.NewLine };
string[] textArray = value.Split(newLineArray, StringSplitOptions.None);
bool first = true;
foreach (var line in textArray)
{
if (!first)
{
run.Append(new Break());
}
first = false;
Text txt = new Text();
txt.Text = line;
run.Append(txt);
}
main.Document.Body.Append(run);
but unfortunately this breaks the WordDocument and I can´t open it anymore :-/ 但不幸的是,这打断了WordDocument,我再也无法打开它了:-/
Anybody here maybe had the same Problem and has an Idea how I can insert the Text without losing the Plaintext-Formatting (CarriageReturns and Linefeeds)? 这里有人可能遇到相同的问题,并且有一个主意,我该如何在不丢失纯文本格式(CarriageReturns和换行符)的情况下插入文本?
So finally I found a Solution by myself, you can use AltChunk to Insert Plaintext and not losing your formatting :-) 所以最后我自己找到了一个解决方案,您可以使用AltChunk插入纯文本,而不会丢失格式:-)
Here is the Code maybe it helps someone out who has the same Problem ;-) 这是代码,也许它可以帮助遇到相同问题的人;-)
public static void SetNotes(this WordprocessingDocument doc, string value)
{
MainDocumentPart main = doc.MainDocumentPart;
string altChunkId = "AltChunkId" + Guid.NewGuid().ToString().Replace("-", "");
var chunk = main.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.TextPlain, altChunkId);
using (var mStream = new MemoryStream())
{
using (var writer = new StreamWriter(mStream))
{
writer.Write(value);
writer.Flush();
mStream.Position = 0;
chunk.FeedData(mStream);
}
}
var altChunk = new AltChunk();
altChunk.Id = altChunkId;
OpenXmlElement afterThat = null;
foreach (var para in main.Document.Body.Descendants<Paragraph>())
{
if (para.InnerText.Equals("Notes:"))
{
afterThat = para;
}
}
main.Document.Body.InsertAfter(altChunk, afterThat);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.