Importword.cs
上传用户:lanchensha
上传日期:2022-02-27
资源大小:7530k
文件大小:8k
源码类别:

编辑器/阅读器

开发平台:

C#

  1. using System;
  2. using System.Collections;
  3. using System.ComponentModel;
  4. using System.Web;
  5. using System.IO;
  6. using System.Text;
  7. using System.Web.UI;
  8. using System.Text.RegularExpressions;
  9. using DotNetTextBox;
  10. namespace Word_dntb
  11. {
  12.     #region word文档导入编辑器的功能插件
  13.     /// <summary>
  14.     /// word文档导入编辑器的类
  15.     /// </summary>
  16.     public partial class Importword : System.Web.UI.Page
  17.     {
  18.         string wordfile = "";
  19.         public string uploadpath = "";
  20.         protected System.Web.UI.WebControls.HiddenField worddoc;
  21.         protected System.Web.UI.WebControls.FileUpload FileUpload1;
  22.         protected System.Web.UI.WebControls.CheckBox saveword;
  23.         protected System.Web.UI.WebControls.Button btnUpload;
  24.         protected System.Web.UI.WebControls.Button canceloading;
  25.         /// <summary>
  26.         /// 页面的初始化
  27.         /// </summary>
  28.         protected void Page_Load(object sender, EventArgs e)
  29.         {
  30.             if (Request.Cookies["uploadFolder"] != null)
  31.             {
  32.                 uploadpath = Request.Cookies["uploadFolder"].Value.ToLower();
  33.             }
  34.             
  35.             if (!IsPostBack)
  36.             {
  37.                 Response.Expires = -1;
  38.                 if (Request.Cookies["languages"] != null)
  39.                 {
  40.                     ResourceManager.SiteLanguageKey = Request.Cookies["languages"].Value;
  41.                 }
  42.                 else
  43.                 {
  44.                     ResourceManager.SiteLanguageKey = HttpContext.Current.Request.ServerVariables["HTTP_ACCEPT_LANGUAGE"].ToLower().Split(',')[0];
  45.                 }
  46.                 btnUpload.Text = ResourceManager.GetString("importeditor");
  47.                 saveword.Text = ResourceManager.GetString("saveword");
  48.                 canceloading.Text = ResourceManager.GetString("canceloading");
  49.             }
  50.         }
  51.         /// <summary>
  52.         /// 转换word文档为html代码并插入编辑器
  53.         /// </summary>
  54.         protected void wordToHtml()
  55.         {
  56.             Word.ApplicationClass word = new Word.ApplicationClass();
  57.             Type wordType = word.GetType();
  58.             Word.Documents docs = word.Documents;
  59.             // 打开文件
  60.             Type docsType = docs.GetType();
  61.             //应当先把文件上传至服务器然后再解析文件为html
  62.             object fileName = wordfile;
  63.             Word.Document doc = (Word.Document)docsType.InvokeMember("Open",
  64.             System.Reflection.BindingFlags.InvokeMethod, null, docs, new Object[] { fileName, true, true });
  65.             // 转换格式,另存为html
  66.             Type docType = doc.GetType();
  67.             string filename = System.DateTime.Now.Year.ToString() + System.DateTime.Now.Month.ToString() + System.DateTime.Now.Day.ToString() +
  68.             System.DateTime.Now.Hour.ToString() + System.DateTime.Now.Minute.ToString() + System.DateTime.Now.Second.ToString();
  69.             //被转换的html文档保存的位置
  70.             string ConfigPath = HttpContext.Current.Server.MapPath(uploadpath + filename + ".html");
  71.             object saveFileName = ConfigPath;
  72.             docType.InvokeMember("SaveAs", System.Reflection.BindingFlags.InvokeMethod,
  73.             null, doc, new object[] { saveFileName, Word.WdSaveFormat.wdFormatFilteredHTML });
  74.             
  75.             //docType.InvokeMember("Quit", System.Reflection.BindingFlags.InvokeMethod, null, doc, null);
  76.             // 退出 Word
  77.             wordType.InvokeMember("Quit",System.Reflection.BindingFlags.InvokeMethod,null,word,null);
  78.             string line;
  79.             StringBuilder strhtml = new StringBuilder();
  80.             try
  81.             {
  82.                 StreamReader sr = new StreamReader(ConfigPath, System.Text.Encoding.Default);
  83.                 while ((line = sr.ReadLine()) != null)
  84.                 {
  85.                     strhtml.Append(line);
  86.                 }
  87.                 sr.Close();
  88.             }
  89.             catch
  90.             {
  91.                 wordType.InvokeMember("Quit", System.Reflection.BindingFlags.InvokeMethod, null, word, null);
  92.                 StreamReader sr = new StreamReader(ConfigPath, System.Text.Encoding.Default);
  93.                 while ((line = sr.ReadLine()) != null)
  94.                 {
  95.                     strhtml.Append(line);
  96.                 }
  97.                 sr.Close();
  98.             }
  99.             string photoname;
  100.             string content = getBody(strhtml.ToString()).Replace("src=", " src=").Replace(filename + ".files/", Request.CurrentExecutionFilePath.Replace("importword.aspx", "") + uploadpath);
  101.             if (Directory.Exists(Server.MapPath(uploadpath + filename + ".files/")))
  102.             {
  103.                 DirectoryInfo dir = new DirectoryInfo(Server.MapPath(uploadpath + filename + ".files/"));
  104.                 FileInfo[] fis = dir.GetFiles();
  105.                 foreach (FileInfo fi in fis)
  106.                 {
  107.                     //if (!File.Exists(Server.MapPath(uploadpath + fi.Name)))
  108.                     //{
  109.                     photoname = filename + fi.Name.Replace(fi.Extension,"");
  110.                     photoname = photoname + fi.Extension.ToLower();
  111.                     content = content.Replace(fi.Name, photoname);
  112.                     fi.MoveTo(Server.MapPath(uploadpath + photoname)); 
  113.                     //}
  114.                 }
  115.                 Directory.Delete(Server.MapPath(uploadpath + filename + ".files/"), true);
  116.             }
  117.             worddoc.Value = content;
  118.             if (!saveword.Checked)
  119.             {
  120.                 File.Delete(wordfile);
  121.             }
  122.             File.Delete(ConfigPath);
  123.         }
  124.         /// <summary>
  125.         /// 处理上传word文件的操作
  126.         /// </summary>
  127.         public bool uploadWord()
  128.         {
  129.             if (FileUpload1.HasFile)
  130.             {
  131.                 string fileName = FileUpload1.PostedFile.FileName;
  132.                 FileInfo file = new FileInfo(fileName);
  133.                 string extendName = file.Extension.ToLower();
  134.                 try
  135.                 {
  136.                     if (extendName == ".doc")
  137.                     {
  138.                         DateTime now = DateTime.Now;
  139.                         wordfile = System.Web.HttpContext.Current.Server.MapPath(uploadpath + now.DayOfYear.ToString() + FileUpload1.PostedFile.ContentLength.ToString() + extendName);
  140.                         if (!File.Exists(wordfile))
  141.                         {
  142.                             FileUpload1.PostedFile.SaveAs(wordfile);
  143.                         }
  144.                     }
  145.                     else
  146.                     {
  147.                         ClientScript.RegisterStartupScript(typeof(Page), "Key", "alert('" + ResourceManager.GetString("errortype") + "')", true);
  148.                         return false;
  149.                     }
  150.                 }
  151.                 catch
  152.                 {
  153.                     return false;
  154.                 }
  155.                 return true;
  156.             }
  157.             else
  158.             {
  159.                 return false;
  160.             }
  161.         }
  162.         /// <summary>
  163.         /// 过滤页头和页尾
  164.         /// </summary>
  165.         public string getBody(string html)
  166.         {
  167.             string resultStr = "";
  168.             Regex re = new Regex(@"<body[^>]s*[^>]*>(?<text>.*?)</body>", RegexOptions.IgnoreCase);
  169.             MatchCollection mc = re.Matches(html);
  170.             foreach (Match m in mc)
  171.             {
  172.                 resultStr += m.Groups["text"].Value;
  173.             }
  174.             return resultStr;
  175.         }
  176.         /// <summary>
  177.         /// 处理上传按键的操作
  178.         /// </summary>
  179.         protected void btnUpload_Click(object sender, EventArgs e)
  180.         {
  181.             if (uploadpath != "")
  182.             {
  183.                 if (uploadWord())
  184.                 {
  185.                     wordToHtml();
  186.                     ClientScript.RegisterStartupScript(typeof(Page), "Key", "addeditor();", true);
  187.                 }
  188.             }
  189.         }
  190.     }
  191.     #endregion
  192. }