[英]OpenXML 2.5 - WordProcessing - How to copy the styles from template document when creating a new document?
我有一個模板文檔,其中包含一些段落和表格以及與之相關的某些樣式。
我需要根據序列從模板文檔中選擇元素,然后將其附加到新文檔的正文中。 以下是執行復制的我的代碼。 我不知何故也需要復制與元素關聯的樣式。 盡管應用了某些樣式,但字體大小和表格邊框之類的內容並未復制到新文檔上。 任何幫助將非常感激。 謝謝
Dictionary<string, string> sequence = GetSequence();
using (WordprocessingDocument templateDocument = WordprocessingDocument.Open(sourceFileLocation, false))
{
Body templateBody = templateDocument.MainDocumentPart.Document.Body;
using (
WordprocessingDocument wordDoc = WordprocessingDocument.Create(destinationFileLocation,
WordprocessingDocumentType.Document))
{
MainDocumentPart mainPart = wordDoc.AddMainDocumentPart();
mainPart.Document = new Document();
Body wordDocDocBody = mainPart.Document.AppendChild(new Body());
//don't think the below two lines work as I intended.
ThemePart themePart1 = templateDocument.MainDocumentPart.ThemePart;
mainPart.AddPart(themePart1);
foreach (var item in sequence)
{
var block = templateBody.Elements().TakeWhile(x => x.InnerText == item.Key);
foreach (var blockItem in block)
{
wordDocBody.Append(blockItem.CloneNode(true));
}
}
}
}
下面的代碼將具有固定名稱的樣式(在這種情況下為“罐頭”表格樣式)從一個Word文檔復制到另一個。
void CopyTableStyles( WordprocessingDocument source, WordprocessingDocument destination )
{
var sourceStyles = source.MainDocumentPart.StyleDefinitionsPart.RootElement;
var tableStyle = sourceStyles.Descendants<Style>()
.Where<Style>( s => s.StyleName.Val == "Light List - Accent 11")
.First<Style>();
if ( tableStyle != null )
{
var destinationStyles = destination.MainDocumentPart.StyleDefinitionsPart.RootElement;
destinationStyles.AppendChild( tableStyle.CloneNode( true ) );
destination.MainDocumentPart.StyleDefinitionsPart.PutXDocument();
}
return;
}
您應該可以從這里開始工作,以使其變得更強大和更適合您的需求。
編輯:抱歉,PutXDocument是一種擴展方法,最初是從Open XML Developer站點上Eric White的示例之一獲取的。
public static void PutXDocument(this OpenXmlPart part)
{
XDocument xdoc = part.GetXDocument();
if (xdoc != null)
{
// Serialize the XDocument object back to the Package.
using (XmlWriter xw = XmlWriter.Create( part.GetStream( FileMode.Create, FileAccess.Write )))
{
xdoc.Save( xw );
}
}
}
上面的代碼在我當前的“技巧包”中的OpenXmlPart靜態擴展類中-我懷疑自從閱讀White先生提供的博客帖子/示例以來,我沒有更改它。
在這一行: var block = templateBody.Elements().TakeWhile(x => x.InnerText == item.Key);
您僅選擇“ Text
對象。 因此,格式被排除在外。 您還需要將此Text對象的父級復制到新文檔中。 您可能需要將“ Paragraph
子級復制到Run
到Text
,以進行格式復制。
您的問題的解決方案將很大,所以,我只想闡明需要完成的工作,您可以為此編寫代碼,如果遇到困難,可以找回代碼。
如@ tr4nc3所述,請考慮將父級復制到Text
,如果要復制整個段落,請將Paragraph
對象從源復制到目標,否則Run
對象就足夠了。
如果存在將樣式應用於段落的情況,則必須獲取該ParagraphStyle.Val
並使用該引用將Style
對象從StylePart
復制到Destination Object。
我知道這需要完成很多工作,但是,如果您使用Open XML Productivity Tool,它將使您的生活變得更加輕松。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.