1. 程式人生 > >C#實現的word轉html命令列工具

C#實現的word轉html命令列工具

需求

有個CMS系統的詳細資訊的來源是人手工編寫的word文件,需求如下:

  • 文件是手工編輯而成的word文件(.docx)
  • 文件具備一定的基本格式,其中包括標題、圖片、流程圖、簡介、按序號排布的詳細說明
  • 初步只需要將這些文件可以以html頁面的形式呈獻給使用者
  • CMS系統主體結構是基於SpringMVC的

思考

對情況進行了解和思考後,認為可以通過一箇中間程式自動化的將word文件轉換成為excel,遂決定寫個程式來實現這個轉換環節。對於這種純Windows的需求,估計也就是JAVA或者是VS系列語言更加方便一些。最近的專案使用的語言主要是JAVA、VC++,C#還沒有嘗試過完成實際專案,於是打算用C#嘗試實現一下。

流程圖(沒有難度,主要是練手)

Created with Raphaël 2.1.0開始從命令列引數讀取輸入的word文件是否有word文件名輸入?檢查檔案是否存在初始化Office元件的app和doc物件將文件讀入doc物件將doc物件另存為html文件開啟並讀入剛才存好的html文件作一些後續的字串處理寫回並關閉html文件結束yesnoyesno

實現程式碼

using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using
Word = Microsoft.Office.Interop.Word; using Microsoft.Office.Interop.Word; namespace word2html { class Program { static void Main(string[] args) { if (args.Length < 1) { Console.WriteLine("說明:本程式用於將word文件轉換為html格式文件,支援.doc和.docx格式"
); Console.WriteLine("用法:word2html.exe <待轉換的word文件>"); Console.WriteLine("Copyleft(C)2015 Solomon"); Console.ReadLine(); return; } string srcInputName = args[0]; // 開啟檔案的位置 string ext = Path.GetExtension(srcInputName); string current_cmd = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName; string current_dir = Path.GetDirectoryName(current_cmd); Console.WriteLine("正在生成html,請稍候..."); string inputName = current_dir + "\\" + srcInputName; string outputName = inputName.Replace(ext, ".html"); // 同路徑儲存 if (File.Exists(inputName)) { object oMissing = System.Reflection.Missing.Value; object oTrue = true; object oFalse = false; Word._Application oWord = new Word.Application(); Word._Document oWordDoc = new Word.Document(); oWord.Visible = false; object openFormat = Word.WdOpenFormat.wdOpenFormatAuto; object openName = inputName; try { oWordDoc = oWord.Documents.Open(ref openName, ref oMissing, ref oTrue, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref openFormat, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing); } catch (Exception e) { Console.WriteLine("讀取Word文件時發生異常"); oWord.Quit(ref oTrue, ref oMissing, ref oMissing); return; } object saveFileName = outputName; object saveFormat = Word.WdSaveFormat.wdFormatFilteredHTML; oWordDoc.SaveAs(ref saveFileName, ref saveFormat, ref oMissing, ref oMissing, ref oFalse, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing); oWordDoc.Close(ref oTrue, ref oMissing, ref oMissing); oWord.Quit(ref oTrue, ref oMissing, ref oMissing); Encoding enc = Encoding.GetEncoding("GB2312"); string s = File.ReadAllText(outputName, enc); s = s.Replace("position:absolute;", ""); File.WriteAllText(outputName, s, enc); Console.WriteLine("Word文件已轉換為html格式"); } } } }

後記

1 尤其需要字符集的問題,在windows下使用的漢字相容字符集事實上是GB2312-80字符集(code page : CP20936)
2 對於“後續的字串處理”環節,該設計的主要原因是因為頁面上因為css絕對定位不準的問題造成了圖片內容對於文字內容的遮擋,之後還應該根據實際需求進行進一步的調整