2016年4月13日 星期三

Open XML SDK 利用範本產生WORD

因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 安裝方式
  1. 手動下載方式
    • 下載位址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)
  2. 使用NuGet
    • 在套件管理器輸入install-package documentformat.openxml,會抓取最新版,如要裝舊版的在後面加上-Version 1.0.0。
另外要再加入WindowsBase的.NET參考。

  1. using DocumentFormat.OpenXml;
  2. using DocumentFormat.OpenXml.Packaging;
  3. using DocumentFormat.OpenXml.Wordprocessing;
  4.  
  5. ///
  6. /// 複製範本並取出內容的部分
  7. ///
  8. ///
  9. ///
  10. ///
  11. ///
  12. private void CopyWordFile(string fromWordFile, string toWordFile, out string templateText)
  13. {
  14. if (File.Exists(toWordFile)) {
  15. File.Delete(toWordFile);
  16. }
  17. //
  18. File.Copy(fromWordFile, toWordFile);
  19. //
  20. using (WordprocessingDocument fromDoc = WordprocessingDocument.Open(toWordFile, true)) {
  21. templateText = fromDoc.MainDocumentPart.Document.Body.InnerXml;
  22. fromDoc.MainDocumentPart.Document.RemoveAllChildren();
  23. }
  24. }
  25.  
  26. ///
  27. /// 設定WORD檔需要的參數
  28. ///
  29. ///
  30. ///
  31. ///
  32. private void SetWordDictionary(string templateText, out string docText)
  33. {
  34. Dictionary keyWordDict = new Dictionary();
  35. keyWordDict.Add("SEQTXT", 1);
  36. keyWordDict.Add("YEARXX", "105");
  37. keyWordDict.Add("DEPTNM", "部門");
  38. keyWordDict.Add("PLANNM", "計畫");
  39. keyWordDict.Add("DATEXX", "日期");
  40. keyWordDict.Add("BGTWTT", "金額");
  41. //
  42. ReplaceTemplateString(keyWordDict, templateText, docText);
  43. }
  44. ///
  45. /// 將WORD檔所設定的參數取代掉
  46. ///
  47. ///
  48. ///
  49. ///
  50. ///
  51. private void ReplaceTemplateString(Dictionary keyWordDict, string templateText, out string docText)
  52. {
  53. foreach (KeyValuePair item in keyWordDict) {
  54. Regex regex = new Regex(item.Key);
  55. templateText = regex.Replace(templateText, item.Value);
  56. }
  57. //
  58. docText += templateText;
  59. }
  60. ///
  61. /// 將XML的文字寫入到WORD檔
  62. ///
  63. ///
  64. ///
  65. ///
  66. private void SetWordFile(string toFileName, string docText)
  67. {
  68. using (WordprocessingDocument toDoc = WordprocessingDocument.Open(toFileName, true)) {
  69. MainDocumentPart mainPart = toDoc.MainDocumentPart;
  70. Body insertBody = mainPart.Document.AppendChild(new Body());
  71. insertBody.InnerXml = docText;
  72. }
  73. }
在實作過程也遇到一些問題
  1. 當WORD檔裡有插入文字方塊時,複製出來的XML再貼回去產出來MSWord會說有錯誤,但強制開還是可以開。
  2. WORD範本檔在複製的時候,格式會有點錯亂,有的正常有的又不正常,後來我的WORD範本用Table來排版就比較正常,不知道是MSWord的問題還是Xml的格式問題。
參考文件:Creating Documents by Using the Open XML

沒有留言 :

張貼留言