在C#中将HTML转换为Docx

21
我想在C#中将一个HTML页面转换为DOCX文件,我该怎么做?

1
https://dev59.com/wHVD5IYBdhLWcg3wRpeX - Pranay Rana
9个回答

19

我的解决方案使用Html2OpenXmlDocumentFormat.OpenXmlHtml2OpenXml的NuGet包在此处)为ASP.NET MVC提供了一种优雅的解决方案。

WordHelper.cs

public static class WordHelper
{
    public static byte[] HtmlToWord(String html)
    {
        const string filename = "test.docx";
        if (File.Exists(filename)) File.Delete(filename);

        using (MemoryStream generatedDocument = new MemoryStream())
        {
            using (WordprocessingDocument package = WordprocessingDocument.Create(
                   generatedDocument, WordprocessingDocumentType.Document))
            {
                MainDocumentPart mainPart = package.MainDocumentPart;
                if (mainPart == null)
                {
                    mainPart = package.AddMainDocumentPart();
                    new Document(new Body()).Save(mainPart);
                }

                HtmlConverter converter = new HtmlConverter(mainPart);
                Body body = mainPart.Document.Body;

                var paragraphs = converter.Parse(html);
                for (int i = 0; i < paragraphs.Count; i++)
                {
                    body.Append(paragraphs[i]);
                }

                mainPart.Document.Save();
            }

            return generatedDocument.ToArray();
        }
    }
}

控制器

    [HttpPost]
    [ValidateInput(false)]
    public FileResult Demo(CkEditorViewModel viewModel)
    {
        return File(WordHelper.HtmlToWord(viewModel.CkEditorContent),
          "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
    }

我正在使用CKEditor来生成此示例的HTML。


12

以下代码做的事情与Luis代码相同,但更易读,并应用于一个ASP.NET MVC应用程序:

var word = new Microsoft.Office.Interop.Word.Application();
word.Visible = false;

var filePath = Server.MapPath("~/MyFiles/Html2PdfTest.html");
var savePathPdf = Server.MapPath("~/MyFiles/Html2PdfTest.pdf");
var wordDoc = word.Documents.Open(FileName: filePath, ReadOnly: false);
wordDoc.SaveAs2(FileName: savePathPdf, FileFormat: WdSaveFormat.wdFormatPDF);

您还可以以其他格式保存,例如像这样的docx:

var savePathDocx = Server.MapPath("~/MyFiles/Html2PdfTest.docx");
var wordDoc = word.Documents.Open(FileName: filePath, ReadOnly: false);
wordDoc.SaveAs2(FileName: savePathDocx, FileFormat: WdSaveFormat.wdFormatXMLDocument);

2
记得在使用完文档后调用 wordDoc.Close()wordDoc.Quit() 方法以释放对象,否则你将会有许多 word 进程在后台运行。 - Dan Diplo
5
请注意,Microsoft 正式不支持在 ASP.NET 应用程序中使用 Interop.Word.Application ,并且不建议这样做。参考链接:https://stackoverflow.com/a/8709255/87698 - Heinzi

4

使用该代码进行转换

Microsoft.Office.Interop.Word.Application word = 
    new Microsoft.Office.Interop.Word.Application();
Microsoft.Office.Interop.Word.Document wordDoc = 
    new Microsoft.Office.Interop.Word.Document();
Object oMissing = System.Reflection.Missing.Value;
wordDoc = word.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing);
word.Visible = false;
Object filepath = "c:\\page.html";
Object confirmconversion = System.Reflection.Missing.Value;
Object readOnly = false;
Object saveto = "c:\\doc.pdf";
Object oallowsubstitution = System.Reflection.Missing.Value;

wordDoc = word.Documents.Open(ref filepath, ref confirmconversion, 
    ref readOnly, 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);
 object fileFormat = WdSaveFormat.wdFormatPDF;
 wordDoc.SaveAs(ref saveto, ref fileFormat, ref oMissing, ref oMissing, ref oMissing,
     ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
     ref oMissing, ref oMissing, ref oMissing, ref oallowsubstitution, ref oMissing,
     ref oMissing);

2

1

0

可以查看使用Aspose.Words for .NET将HTML转换为Word文档的示例。 - Shahzad Latif
1
我在使用ASPOSE将HTML转换为DOCX时遇到了一些问题,例如样式和图像格式问题,这些问题对我来说似乎非常基本,但他们认为这是产品的限制... - Ariel
同意。即使是嵌入式的CSS,缺乏对CSS的支持意味着您必须自己格式化所有表格、段落甚至列表。 - nullnvoid

0

MigraDoc可以帮助您。 或者使用VS工具进行Office开发。 或通过COM连接到Office。


0

微软不建议在 Web 服务器上使用办公应用程序。但是,使用 OpenXML 2.5 可以相对容易地实现。

你只需要通过 ("<", ">") 分割 HTML,然后将每个部分放入 switch 中,并确定它是否为 HTML 标记即可。

然后,你可以开始将每个部分转换为 "Run" 和 "RunProperties" 的 HTML,而非 HTML 文本则简单地放置在 "Text" 中。

听起来比实际要难...是的,我也不知道为什么没有可用的代码可以完全做到这一点。

需要注意的事项。 两种格式不能干净地相互转换,因此,如果你专注于编写最干净的代码,则会遇到格式本身变得混乱的问题。


-2
你可以考虑使用 PHPDocX ,这是一个非常方便的工具,可以将 HTML 文件和/或 HTML 字符串转换为 WordML。
它有很多选项,其中包括:
  1. 您可以使用 CSS 样式选择器过滤哪些 HTML 片段应该插入到 Word 文档中。
  2. 您可以选择下载图像或将它们作为外部链接。
  3. 它解析 HTML 表单。
  4. 您可以使用原始 CSS 覆盖本机 Word 样式,用于表格和段落。
  5. 将 HTML 锚点转换为 Word 书签。
  6. 等等
我希望你觉得它有用 :-)

2
这与C#无关,而是涉及PHP。 请回答OP所问的问题。 - Sha

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接