using Word = Microsoft.Office.Interop.Word; using System.Diagnostics; using Logger = Log.Log; namespace WordAnalyze { public class Analyze { public Analyze() { } public static string splitChar = "---"; public string path = ""; public void SetPath(string path) { this.path = path; } public string AnalyzeFile(string fileName) { if (!ValidFileName(fileName)) { Logger.D("AnalyzeFile with invalid file name {0}", fileName); return "无效的文件名"; } object fn = fileName; Word.ApplicationClass app = new Word.ApplicationClass(); // 打开word应用,只会打开一个,即单例模式 Word.Document doc = null; // 源word文件对象 try { doc = app.Documents.Open(ref fn); doc.Paragraphs.Add(); Word.Paragraphs garapraph = doc.Paragraphs; // 源文件的内容 bool insert = false; //判断是否有插入数据到新文档中,如果有则保存新word,否则直接关掉新word int fileIndex = 1; // 切割后word的文件序号,例子: test1.doc, test2.doc Word.Document newDoc = null; newDoc = app.Documents.Add(); // 遍历word,通过 --- 三个横线分割 for (int index = 1; index < garapraph.Count; index ++) { string text = garapraph[index].Range.Text.ToString(); // Logger.D("document parapraph with index({0}) get message ({1})", index, garapraph[index].Range.Text.ToString()); text = text.Trim(); if (splitChar == text) { if (insert) { object file = Rename(fileName, fileIndex++); newDoc.SaveAs2(file); } newDoc.Close(); newDoc = app.Documents.Add(); insert = false; continue; } garapraph[index].Range.Select(); app.Selection.Copy(); app.Documents[1].Activate(); app.Selection.Paste(); insert = true; } if (insert) { object file = Rename(fileName, fileIndex++); newDoc.SaveAs2(file); } newDoc.Close(); insert = false; } catch (System.Exception e) { Logger.E("analyze with file name({0}) error ->({1})", fileName, e.Message.ToString()); return e.Message.ToString(); } finally { if (doc != null) { doc.Undo(); doc.Close(); } if (app != null) { app.Quit(); } } return ""; } // 判断文件后缀名是否是.doc 或者.docx public bool ValidFileName(string fileName) { if (fileName == null || fileName.Length < 1) { return false; } if (!fileName.EndsWith(".doc") && !fileName.EndsWith(".docx")) { return false; } return true; } // 用设定的目录当做子word的目录,默认为选择文件的目录 public string Rename(string filename, int index) { var filePathIndex = filename.LastIndexOf('\\'); string name = ""; string tempPath = ""; if (-1 != filePathIndex) { name = filename.Substring(filePathIndex); if (name.Length > 0) { name = name.Substring(1); } tempPath = filename.Substring(0, filePathIndex); } if ("" == path) { path = tempPath; } string newFilename = name; newFilename = path + "\\" + name; int lastIndex = newFilename.LastIndexOf('.'); string newName = ""; if (-1 != lastIndex) { newName = string.Format("{0}{1}{2}", newFilename.Substring(0, lastIndex), index, newFilename.Substring(lastIndex)); } else { newName = string.Format("{0}{1}", newFilename, index); } return newName; } } }