123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126 |
- using Word = Microsoft.Office.Interop.Word;
- using System.Diagnostics;
- using Logger = Log.Log;
- namespace WordAnalyze
- {
- public class Analyze
- {
- public Analyze()
- {
- }
- public static string splitChar = "---";
- // 将word根据指定的值切割成多个word
- public string AnalyzeAndCut()
- {
- return "";
- }
- 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);
- 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;
- Logger.D("documents count is {0}", app.Documents.Count);
- }
- 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.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;
- }
- public string WriteFile(string filename)
- {
- return "";
- }
- public string Rename(string filename, int index)
- {
- int lastIndex = filename.LastIndexOf('.');
- string newFilename = string.Format("{0}{1}{2}", filename.Substring(0, lastIndex), index, filename.Substring(lastIndex));
- return newFilename;
- }
- }
- }
|