Aspose.Words应用笔记

锺宜
2023-12-01

之前某项目需要用到读取识别word内容,一开始使用 Microsoft.Office.Interop.Word类库,将word文档转化为html文档,,再读取分析html内容。
具体代码如下:

        /// <summary>
        /// 把Word文档转化为Html文件
        /// </summary>
        /// <param name="wordFileName">word完整文件名</param>
        /// <param name="htmlFileName">要保存的完整html文件名</param>
        /// <returns></returns>
        public  void WordToHtml(string wordFileName, string htmlFileName)
        {
            
            try
            {
                Object oMissing = System.Reflection.Missing.Value;
                _Application WordApp = new Application();
                WordApp.Visible = false;
                object filename = wordFileName;
                _Document WordDoc = WordApp.Documents.Open(ref filename, ref oMissing,
                    ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                    ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
                // 打开文件
                Type docsType = WordApp.Documents.GetType();
                // 转换格式,另存为
                Type docType = WordDoc.GetType();
                object saveFileName = htmlFileName;
                docType.InvokeMember("SaveAs", System.Reflection.BindingFlags.InvokeMethod, null, WordDoc,
                    new object[] { saveFileName, WdSaveFormat.wdFormatHTML });
                //保存
                WordDoc.Save();
                //关闭文档  
                WordDoc.Close(ref oMissing, ref oMissing, ref oMissing);
                WordApp.Quit(ref oMissing, ref oMissing, ref oMissing);
                //转化为html之后需要在头部增加编码
                 StreamReader sr = new StreamReader(strFilePath, Encoding.Default);
                string html = sr.ReadToEnd();
                sr.Close();
                html = Regex.Replace(html, @"<meta[^>]*>", "<meta http-equiv=Content-Type content='text/html; charset=gb2312'>", RegexOptions.IgnoreCase);
                System.IO.StreamWriter sw = new StreamWriter(strFilePath, false, Encoding.Default);
                sw.Write(html);
                sw.Close();
            }
            catch (Exception e)
            {
            }
        }
缺点
1.服务器上必须安装Microsoft.Office软件
2.每次调用这段代码,会产生一个进程,该进程不会随着文件关闭而关闭,需要手动去关闭。于是调用次数一多,容易造成服务器卡死,转化失败。

于是在我感觉走投无路的时候,发现了Aspose.Words的存在。

Aspose.Words简介

Aspose.Words 是.NET类库,支持Doc,Docx,RTF,HTML,OpenDocument,PDF,XPS,EPUB等格式。使用Aspose.Words不需要安装Microsoft.Word。

Aspose.Words思路解析
1.将文件上传到相应本地文件夹
2.读取文件夹路径,用Aspose.Words解析文件,转化为table节点格式
3.通过节点位置定位获取相应的内容
核心代码如下:

using Aspose.Words;

                string exName = System.IO.Path.GetExtension(FileUpload1.FileName); //得到扩展名
                if (exName != ".doc")
                    Label1.Text = "你上传的不是word文档,无法进行转换";
                else
                {
                    try
                    {
                        StringBuilder myStr = new StringBuilder();
                        string path = Server.MapPath("/UploadFiles/Temp/");  //当前路径
                        string fileName = Guid.NewGuid().ToString() + ".doc";  //传入的word文档重命名
                        string fileName_html = Guid.NewGuid().ToString() + ".html";  //转化后的html名称
                        FileUpload1.PostedFile.SaveAs(path + fileName);
                        
                        Document doc = new Document(path + fileName);  //解析word文档
                        content = doc.GetText(); //获取文档中所有文字
                        //提取文档中的具体文字信息
                        //分节点层层寻找,直至定位到需要找的字段
                        var table_all = doc.Sections[0].Body.GetChild(NodeType.Table, 1, false) as Table; //获取当前节点下的第二个子table
                        var table_node1 = table_all.Rows[0].Cells[0].GetChild(NodeType.Table, 0, false) as Table; //获取该节点第一行第一列的第一个子table
                        var name_info = table_node1.Rows[0].Cells[1].GetChild(NodeType.Table, 0, false) as Table;
                        var a =name_info.Rows[0].Cells[0].GetText();  //获取当前节点(包含该节点的子节点)的文字内容
                        var _name = Regex.Split(_name_info.Rows[0].Cells[0].GetText(), "流程状态", RegexOptions.IgnoreCase)[0]; //截取字段
                        //将文档转化为html页面(方便预览)
                        doc.Save(path+fileName_html, SaveFormat.Html);
                    }
                    catch (Exception ex)
                    {
                        var log = ex.Message;
                    }
               }

此外,Aspose.Words还支持将网页上面的word文档直接解析,转化为html
核心代码如下:

var FileName="abc.docx";
Document doc = new Document("http://www.abc.com/uploadfiles/" +FileName);
string path = Server.MapPath("/UploadFiles/Temp/"); //当前路径
doc.Save (path +"abc.html", SaveFormat.Html);//转存为html

总结:

  1. 优点:不需要安装office组件,转化为table使用节点定位,获取的准确率较高
  2. 缺点:只能针对某一类型的文档模板,不同模板节点位置不一样,需要重新写代码定位节点,通用性较差
 类似资料: