2013-04-30 38 views
1

我與我們公司的Normal.dotm有關的東亞屬性styles.xml有問題。如果你有興趣,你可以找到a history of the issue here。我們不能只在整個公司範圍內替換模板而不覆蓋自定義樣式/宏等。我幾乎沒有使用OpenXML的經驗,但我認爲它可以解決這個問題。但是,我發現的所有文章和教程都沒有太多幫助。他們都參考了「文檔」部分,並專注於改變內容而不是元素和屬性。在OpenXML中編輯eastAsia屬性

基本上,我需要遍歷每個<w:rFonts>元素,改變從"Times New Roman"w:eastAsia屬性"MS Mincho."這是我自信的唯一部分約:

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

namespace eastAsiaFix 
{ 
    class Program 
    { 
    static void Main(string[] args) 
    { 
     using (WordprocessingDocument myDocument = WordprocessingDocument.Open(@"C:\users\" + Environment.UserName + @"\Desktop\eastAsiaFix.dotm", true)) 
     { 
      StyleDefinitionsPart styles = myDocument.MainDocumentPart.StyleDefinitionsPart; 

      if (styles == null) 
      { 
       return; 
      } 
     } 

    } 
    } 
} 

我想我需要的是類似如下:

foreach (OpenXMLElement theStyle in styles.Styles.ChildElements) 
{ 
    if (theStyle.LocalName = "style") 
    { 
     theStyle.StyleRunProperties.RunFonts.EastAsia.Value = "MS Mincho"; //faking this 
    } 
} 

我怎麼到w:rFonts節點並編輯eastAsia屬性?

回答

1

我能想到兩種不同的解決方案來改變東亞字體的值的值。 第一個解決方案僅改變 集合下的東亞字體的值,集合爲Styles。此解決方案還將更改文檔默認段落和運行屬性(DocDefaults類,w:docDefaults)的東亞 字體值。

using (WordprocessingDocument myDocument = WordprocessingDocument.Open(@"C:\users\" + Environment.UserName + @"\Desktop\eastAsiaFix.dotm", true)) 
{ 
    StyleDefinitionsPart stylesPart = myDocument.MainDocumentPart.StyleDefinitionsPart; 

    if (stylesPart == null) 
    { 
    Console.Out.WriteLine("No styles part found."); 
    return; 
    } 

    foreach(var rf in stylesPart.Styles.Descendants<RunFonts>()) 
    {   
    if(rf.EastAsia != null) 
    { 
     Console.Out.WriteLine("Found: {0}", rf.EastAsia.Value); 
     rf.EastAsia.Value = "MS Mincho"; 
    }   
    }  
} 

第二個解決方案是隻爲樣式定義改變東亞字體值 (而不是文件默認段落和運行性能):

using (WordprocessingDocument myDocument = WordprocessingDocument.Open(@"C:\users\" + Environment.UserName + @"\Desktop\eastAsiaFix.dotm", true)) 
{ 
    StyleDefinitionsPart stylesPart = myDocument.MainDocumentPart.StyleDefinitionsPart; 

    if (stylesPart == null) 
    { 
    Console.Out.WriteLine("No styles part found."); 
    return; 
    } 

    foreach(var style in stylesPart.Styles.Descendants<Style>()) 
    {   
    foreach(var rf in style.Descendants<RunFonts>()) 
    { 
     if(rf.EastAsia != null) 
     { 
     Console.Out.WriteLine("Found: {0}", rf.EastAsia.Value); 
     rf.EastAsia.Value = "MS Mincho"; 
     } 
    }    
    }  
} 
+0

謝謝,@Hans !我使用第二種解決方案來避免更改默認設置,這不是問題。它效果很好! 如果你不介意我的問題,爲什麼你使用「var Style」和「var rf」而不是「Style style」和「RunFonts rf?」?這是我在試用不同的「foreach」語句時掛上的一件事。 – tmoore82 2013-05-01 16:24:23

+0

@ tmoore82:哦,這只是我個人的偏好。您也可以顯式鍵入變量。 – Hans 2013-05-01 18:28:46

+0

很酷。再次感謝! – tmoore82 2013-05-01 22:51:23