123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122 |
- using Word = Microsoft.Office.Interop.Word;
- using System.Diagnostics;
- using Logger = Log.Log;
- namespace WordAnalyze
- {
- public class Analyze
- {
- public Analyze()
- {
- }
- // 将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.Document doc = null;
- try
- {
- doc = app.Documents.Open(ref fn);
- var oDoc = app.Documents.Add();
- //Insert a paragraph at the beginning of the document.
- var paragraph1 = oDoc.Content.Paragraphs.Add();
- Word.Paragraphs garapraph = doc.Paragraphs;
- for (int i = 1; i < garapraph.Count; i++)
- {
- Logger.D("-- {0}", garapraph[i].Range.Text.ToString());
- garapraph[i].Range.Select();
- app.Selection.Copy();
- app.Selection.Paste();
- //var tempDoc = app.Documents.Add(oDoc);
- //tempDoc.Content.Paragraphs.Add();
- app.Documents[1].Activate();
- app.Selection.Paste();
- //tempDoc.SaveAs2(Rename(fileName, i));
- //tempDoc.Close();
- Logger.D("selection --- {0}", app.Selection.ToString());
- }
- Logger.D("documents count is {0}", app.Documents.Count);
- doc.Save();
- doc.SaveAs2(@"E:\test\test2222.doc");
- var file = Rename(fileName, 1000);
- object objectFilename = file;
- //paragraph1.Range.Text = "Heading 1";
- //paragraph1.Range.Font.Bold = 1;
- //paragraph1.Format.SpaceAfter = 24; //24 pt spacing after paragraph.
- oDoc.SaveAs2(objectFilename);
- }
- 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;
- }
- }
- }
|