写个方法为upLoadWord,然后再写上我所需要的条件。 public ActionResult upLoadWord(HttpPostedFileBase file) { ReturnJsonVo returnJson = new ReturnJsonVo(); if (file != null) { 判断导入的文件类型是否正确 获取它的文件扩展名 string fileExtension = Path.GetExtension(file.FileName); 用if判断一下: if ("(.doc)|(.docx)".Contains(fileExtension)) { 自定义文件名 string fileName = DateTime.Now.ToString (“yyyyMMddHHmmss”) + file.FileName; 将word文档保存到指定的文件夹下 判断路径是否存在,若存在则直接拼接路径,否则创建路径再拼接 if (!Directory.Exists(Server.MapPath("~/Document/Title/Temp/"))) {Directory.CreateDirectory(Server.MapPath("~/Document/Title/Temp/"));} 拼接存放word文档的路径 string filePath = Path.Combine(Server.MapPath ("~/Document/Title/Temp/"), fileName); string filePath = Server.MapPath("~/Document/Title/Temp/") + fileName; 保存文件 file.SaveAs(filePath); 将word文件转化为html文件并保存到指定路径下 设置文件转化为HTML文件后的名称,后缀替换为.html string htmlName = fileName.Replace(fileExtension, “.html”); 拼接存放文件的路径 string htmlPath = Path.Combine(Server.MapPath("~/Document/Title/Temp/"), htmlName); /**Spire.Doc for .NET是一款由E-iceblue公司开发的专业的Word .NET类库, 使用该工具开发人员可以在任意.NET平台(C#,VB.NET,ASP.NET)上快速创建,读取,写 入,转换,打印Word文档。 作为一个独立的Word 组件,Spire.Doc的运行无需安装Microsoft Word。 而且,它可以将Microsoft Word文档创建功能集成到开发者的任何.NET应用程序 Spire.Doc.for .NET 是一个专业的word .NET库 ˈspaɪə® **/ 将文件读取到document中 Document document = new Document(filePath); 将文件转化为html格式并保存到指定的路径下 document.SaveToFile(htmlPath, FileFormat.Html); 读取文件内容,ReadAllText读取文件中所有的字符串 string strHtml = System.IO.File.ReadAllText(htmlPath); 将标签中所有的样式去掉 strHtml = Regex.Replace(strHtml, “style=”.+? (?= “)”", “”); 将HTML中的
与
替换为带有自定义属性的p标签 strHtml = Regex.Replace(strHtml, “<p|<pre”, “<p reg=“demo””); strHtml = Regex.Replace(strHtml, “”, “ ”); 提取所有的P标签 \w\W基本选择了所有的字符 \r表示回车:光标回到行首,不换行;\n表示换行:光标下移一行,不回行首 \r\n一般是组合使用 MatchCollection matchesPList = Regex.Matches(strHtml, “<p reg=“demo”[\w\W\r\n]*?”); 声明一个键值对集合的列表保存最终结果 Dictionary 表示泛型集合 Dictionary<string, string> 表示键值对的集合 List<Dictionary<string, string>> listResult = new List<Dictionary<string, string>>(); 提取p标签的文字图片内容 for (var i = 1; i < matchesPList.Count; i++) {获取P标签以及内容,作为后面方法调用的参数 string strP = matchesPList[i].Value; 获取P标签里面内容的方法 string txtContent = FormateHandler(strP); 声明键值对集合 Dictionary<string, string> dic = new Dictionary<string, string>(); dic.Add(i.ToString(), txtContent); listResult.Add(dic); } 声明存放输出数据的变量 string strOutHtml = “”; foreach (Dictionary<string, string> listItem in listResult){ foreach (string item in listItem.Values) { strOutHtml += item; } strOutHtml += “”;} 将处理后的结果,构建成最终显示的html returnJson.State = true; returnJson.Text = strOutHtml; } else{returnJson.State = false; returnJson.Text = “上传的文件不是word类型的文档,请选择word类型文件”; }} else {returnJson.State = false; returnJson.Text = “导入的文件为空!”;} return Json(returnJson, JsonRequestBehavior.AllowGet);}