因Office已經標準化成XML格式,要產出標準的Office 2007以上的格式就不可使用舊有的Office Library來產生,這次的專案需求是要利用一個範本檔(docx)作套表產出,是要複製範本的格式,依據資料筆數看要貼幾頁,找到此類別庫Open XML SDK來產出。
目前最新的版本是Open XML SDK 2.5是.NET4.0以上,因專案只到.NET3.5,故使用Open XML SDK 2.0版
Open XML SDK 安裝方式
- 手動下載方式
- 下載位址2.5
- 下載位址2.0
- 預設安裝路徑為C:\Program Files (x86)\Open XML SDK\
- 下載完有兩個檔案,一個是主要的DLL檔,另一個是他的工具,工具可以將Office檔案載入,可轉換C#的Code出來,幫你把產生此檔案的程式碼產出來,根本就是程式碼產生器,太方便了吧~~
- 手動將此DLL載入(C:\Program Files (x86)\Open XML SDK\2.0\lib\DocumentFormat.OpenXml.dll)
- 使用NuGet
- 在套件管理器輸入install-package documentformat.openxml,會抓取最新版,如要裝舊版的在後面加上-Version 1.0.0。
另外要再加入WindowsBase的.NET參考。
- using DocumentFormat.OpenXml;
- using DocumentFormat.OpenXml.Packaging;
- using DocumentFormat.OpenXml.Wordprocessing;
-
- ///
- /// 複製範本並取出內容的部分
- ///
- ///
- ///
- ///
- ///
- private void CopyWordFile(string fromWordFile, string toWordFile, out string templateText)
- {
- if (File.Exists(toWordFile)) {
- File.Delete(toWordFile);
- }
- //
- File.Copy(fromWordFile, toWordFile);
- //
- using (WordprocessingDocument fromDoc = WordprocessingDocument.Open(toWordFile, true)) {
- templateText = fromDoc.MainDocumentPart.Document.Body.InnerXml;
- fromDoc.MainDocumentPart.Document.RemoveAllChildren();
- }
- }
-
- ///
- /// 設定WORD檔需要的參數
- ///
- ///
- ///
- ///
- private void SetWordDictionary(string templateText, out string docText)
- {
- Dictionary keyWordDict = new Dictionary();
- keyWordDict.Add("SEQTXT", 1);
- keyWordDict.Add("YEARXX", "105");
- keyWordDict.Add("DEPTNM", "部門");
- keyWordDict.Add("PLANNM", "計畫");
- keyWordDict.Add("DATEXX", "日期");
- keyWordDict.Add("BGTWTT", "金額");
- //
- ReplaceTemplateString(keyWordDict, templateText, docText);
- }
- ///
- /// 將WORD檔所設定的參數取代掉
- ///
- ///
- ///
- ///
- ///
- private void ReplaceTemplateString(Dictionary keyWordDict, string templateText, out string docText)
- {
- foreach (KeyValuePair item in keyWordDict) {
- Regex regex = new Regex(item.Key);
- templateText = regex.Replace(templateText, item.Value);
- }
- //
- docText += templateText;
- }
- ///
- /// 將XML的文字寫入到WORD檔
- ///
- ///
- ///
- ///
- private void SetWordFile(string toFileName, string docText)
- {
- using (WordprocessingDocument toDoc = WordprocessingDocument.Open(toFileName, true)) {
- MainDocumentPart mainPart = toDoc.MainDocumentPart;
- Body insertBody = mainPart.Document.AppendChild(new Body());
- insertBody.InnerXml = docText;
- }
- }
在實作過程也遇到一些問題
-
當WORD檔裡有插入文字方塊時,複製出來的XML再貼回去產出來MSWord會說有錯誤,但強制開還是可以開。
-
WORD範本檔在複製的時候,格式會有點錯亂,有的正常有的又不正常,後來我的WORD範本用Table來排版就比較正常,不知道是MSWord的問題還是Xml的格式問題。
參考文件:
Creating Documents by Using the Open XML