更新2014年1月
我有由我自己寫的功能。不確定這是否是最好的方式,所以請檢查並評論。
private readonly IDictionary<WdBuiltinStyle, string> _localStyleNames = new Dictionary<WdBuiltinStyle, string>();
private readonly IDictionary<Style, string> _defaultStyleNames = new Dictionary<Style, string>();
private string GetLocalizedName(WdBuiltinStyle wd) {
return _localStyleNames[wd];
}
private string GetLocalizedName(Style wd) {
return _defaultStyleNames[wd];
}
internal bool CheckLocalizedStyleName(Style style, WdBuiltinStyle wd) {
var styleName = style.NameLocal;
return GetLocalizedName(wd).Contains(styleName);
}
private void LocalizedNames() {
Globals.ThisAddIn.Application.ScreenUpdating = false;
if (!_localStyleNames.Any()) {
// create a test object
// Move this to start up routine to get localized names
foreach (var wd in Enum.GetValues(typeof (WdBuiltinStyle))) {
object s = (WdBuiltinStyle) wd;
Paragraph testPar = null;
try {
testPar = CurrentDocument.Paragraphs.Add();
testPar.set_Style(ref s);
var headingStyle = (Style) testPar.get_Style();
CurrentDocument.Paragraphs[CurrentDocument.Paragraphs.Count].Range.Delete();
var headingStyleName = headingStyle.NameLocal;
_localStyleNames.Add((WdBuiltinStyle) s, headingStyleName);
}
catch (Exception ex) {
Range testRange = null;
// not a para style, trying range style
try {
testRange = testPar.Range;
testRange.set_Style(ref s);
var rangeStyle = (Style) testRange.get_Style();
var rangeStyleName = rangeStyle.NameLocal;
_localStyleNames.Add((WdBuiltinStyle) s, rangeStyleName);
CurrentDocument.Paragraphs[CurrentDocument.Paragraphs.Count].Range.Delete();
}
catch (Exception) {
// even not range, try table
if (s.ToString().Contains("Table")) {
try {
var t = CurrentDocument.Tables.Add(testRange, 1, 1, null, null);
t.set_Style(ref s);
var tStyle = (Style) t.get_Style();
var tStyleName = tStyle.NameLocal;
_localStyleNames.Add((WdBuiltinStyle) s, tStyleName);
t.Delete();
}
catch (Exception) {
// ignore even this
}
}
}
}
finally {
if (testPar != null) {
testPar.Range.Delete();
}
}
}
}
if (!_defaultStyleNames.Any()) {
// after this, all built in names are present. However, word has some more styles "embedded" and those we catch here
foreach (Style wd in CurrentDocument.Styles) {
_defaultStyleNames.Add(wd, wd.NameLocal);
}
}
Globals.ThisAddIn.Application.ScreenUpdating = true;
}
這種方法只是簡單地通過所有樣式,嘗試逐個應用它,並提取本地化名稱並將其存儲在字典中。加載文檔後需要調用一次。因爲內部樣式不公開獲取樣式的方式,所以我使用異常來處理寫在無效位置的樣式。