如何将html转换为doc而不丢失段落?

时间:2014-06-08 14:29:59

标签: c# html html-agility-pack

我尝试从网站上获取文字。例如http://ahmetturanalkan.net/yazi/laik-cemaatin-kokleri-kadikoyde-mi/

它以纯文本形式导出到word。我的意思是没有                                                                                                   < / p为H.< p为H.这使它没有段落。如何使用适当的段落将其转换为原始网站上的文本?

这是我得到文字的方法

       private string yazial(string s)
    {
        string htmlContent = getsource(s);
        HtmlAgilityPack.HtmlDocument document = new HtmlAgilityPack.HtmlDocument();
        document.LoadHtml(htmlContent);
        var nodlar = document.DocumentNode.SelectSingleNode("*//article").InnerHtml;

        var nodlar1 = document.DocumentNode.SelectSingleNode("*//article/div[@class='page-header']").InnerText;
        //lectSingleNode
        docyap(nodlar,nodlar1);
        return nodlar;
    }

这是我尝试导出word doc

的方法
  private void docyap(string s,string g)
    {
        Microsoft.Office.Interop.Word.Application oWord = new Microsoft.Office.Interop.Word.Application();
        oWord.Visible = true;
        object oMissing = System.Reflection.Missing.Value;

        Microsoft.Office.Interop.Word.Document wBelge = oWord.Documents.Add(ref oMissing, ref oMissing,
        ref oMissing, ref oMissing);    

        Microsoft.Office.Interop.Word.Paragraph baslik = wBelge.Paragraphs.Add(ref oMissing);
        object styleHeading = "Başlık 1";
        baslik.Range.set_Style(styleHeading);
        baslik.Range.Text = g; 

        baslik.Range.InsertParagraphAfter();
        Microsoft.Office.Interop.Word.Paragraph paragraf2;
        paragraf2 = wBelge.Paragraphs.Add(ref oMissing);
        paragraf2.Range.Text = s;
        paragraf2.Range.InsertParagraphAfter();           
        wBelge.SaveAs(ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);

1 个答案:

答案 0 :(得分:0)

我最终使用像

           string yeni = nodlar.Replace("<p>", "    ").Replace("</p>","\n");
           yeni = System.Text.RegularExpressions.Regex.Replace(yeni, "<div(.*)</div>", string.Format(""));
           yeni = System.Text.RegularExpressions.Regex.Replace(yeni, "<div(.*)</a>", string.Format(""));
            yeni = Regex.Replace(yeni, @"<[^>]*>", String.Empty);

但如果它存在,最好知道更整洁的解决方案