手邊的專案涉及多國語系,之前研究過使用Excel維護多國語系字串資源檔,意外發現Office的繁簡轉換功能威猛過人,不單只是置換字元編碼,還能做到詞彙轉換,將字彙轉換成對應的說法,例如: 交易資料->事务数据、預設記憶體->默认内存... 等等,放著神兵利器不用,豈不暴殄天物? 於是,延續先前開發Word套表服務的概念,裝著Word當引擎的裝甲車登場囉~

程式碼的重點在於Word Document物件的共用與資源確實回收(操作Office Interop的注意事項先前也討論過)。至於轉換核心,一行搞定 -- TCSCConverter

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using Microsoft.Office.Interop.Word;
 
public class ChineseStrConverter : IDisposable
{
    private Application wordApp = null;
    private Document doc = null;
 
    public ChineseStrConverter()
    {
        wordApp = new Application();
        wordApp.Visible = false;
        doc = wordApp.Documents.Add();
    }
 
    public string ConvChineseString(string src, bool chs2cht = false)
    {
        string result = null;
        try
        {
            doc.Content.Text = src;
            doc.Content.TCSCConverter(
                chs2cht ? //由參數決定簡->繁或是繁->簡
                WdTCSCConverterDirection.wdTCSCConverterDirectionSCTC : 
                WdTCSCConverterDirection.wdTCSCConverterDirectionTCSC,
                true, true);
            //取回轉換結果時,結尾會多出\r
            result = doc.Content.Text.TrimEnd('\r');
        }
        catch (Exception ex)
        {
            result = "Error: " + ex.Message;
        }
        return result;
    }
 
 
    public void Dispose()
    {
        //確實關閉Word Application
        try
        {
            //關閉Word檔
            object dontSave = WdSaveOptions.wdDoNotSaveChanges;
            ((_Document)doc).Close(ref dontSave);
            //確保Document COM+釋放
            if (doc != null)
                Marshal.FinalReleaseComObject(doc);
            doc = null;
            ((_Application)wordApp).Quit(ref dontSave);
        }
        finally
        {
            Marshal.FinalReleaseComObject(wordApp);
        }
    }
}

不過,詞彙轉換涉及一定複雜度,故得留意轉換效率。網路上有一篇很棒的文章: C# 繁簡轉換效能大車拚,比較了四種不同繁簡轉換方式的速度,其中Word是最慢的,但也是唯一支援詞彙轉換的,所以沒啥好抉擇,了解其執行效率,應用時心裡有數就好。

寫個小程式測試,轉換功能正常,至於速度,在我的環境(CPU i7-2600 + Win2008R2 + Word 2010),對字串(約30個字元)進行200次轉換(繁轉簡、簡轉繁各100次)耗時3.6秒,故每次轉換約18ms;762個字元的繁體文章轉為簡體100次,耗時也差不多3.6秒,每次轉換36ms。此一效能表現用於批次或預先轉換,應是綽綽有餘了!

又到了呼口號時間,大家一起為本日MVP歡呼: Office 好威呀!


Comments

# by NewerCSharp

I have tested on Win10 En,64bit, Office 2016 32 bits English, I didn't see the result. Does Microsoft.Office.Interop.Word require Chinese language pack?

# by Jeffrey

to NewerCSharp, 我沒有試過用英文版 Office 做轉換,查相關文章 https://www.cityu.edu.hk/csc/install-guide/TCSCTranslate-tc.htm 的確有提到要裝 Language Pack。

Post a comment